首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

Python错误处理

2012-09-15 
Python异常处理Python 用异常对象(exception object)来表示异常情况。1. 查看内建的异常类: import exce

Python异常处理
Python 用异常对象(exception object)来表示异常情况。

1. 查看内建的异常类:
   >>> import exceptions
   >>> dir(exceptions)
   所有这些异常都可以用在raise语句中:
   >>> raise ArithmeticError

2. 创建自己的异常类:
   就像其他类一样----只要确保从Exception类继承(不管是间接的或者是直接的,也就是
   说继承其他的内建异常类也是可以的)。
   例如:
class SomeCustomException(Exception): pass

3. 捕捉异常:
   例如:
       

try:    x = input('Enter the first number: ')    y = input('Enter the second number: ')    print x/yexcept ZeroDivisionError:     print "The second number can't be zero!"except TypeError:    print "That wasn't a number, was it?"        

   例如:
       
try:    x = input('Enter the first number: ')    y = input('Enter the second number: ')except (ZeroDivisionError, TypeError, NameError):    print 'You numbers were bogus...'        


4. 捕捉对象:
   例如:
       
try:    x = input('Enter the first number: ')            y = input('Enter the second number: ')    print x/yexcept (ZeroDivisionError, TypeError), e:    print e        


5. 真正的全捕捉:
   例:
       
try:    x = input('Enter the first number: ')    y = input('Enter the second number: ')    print x/yexcept:    print 'Something wrong happened...'        


6. 万事大吉:
   一些坏事发生时执行一段代码,例:
  
   try:       print 'A simple task'   except:       print 'What? Something went wrong?'   else:       print 'Ah... It went as planned.'   

   例:
  
   while True:       try:           x = input('Enter the first number: ')           y = input('Enter the second number: ')           value = x/y           print 'x/y is', value       except:           print 'Invalid input. Please try again.'       else:           break   


7. 最后:
   Finally子句,用来在可能的异常后进行清理,它和try子句联合使用:
  
   x = None   try:       x = 1/0   finally:       print 'Cleaning up...'       del x   


热点排行