python异常处理

来源:互联网 发布:阿里数据分析师年薪 编辑:程序博客网 时间:2024/05/22 03:52
异常处理可以使用raise显式的指定
>>> raise Exception('too many value')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: too many value
使用raise可以在自定义异常的时候显式调用,自定义异常创建一个类,保证类是Exception的子类,例如:
class MyException(Exception):
pass

也可以使用try...except语句来捕获异常,例如除数不能为0
try:
x=input('first number:')
y=input('second number:')
print x/y
except ZeroDivisionError:
print 'canot be 0'
查看有哪些系统定义的异常:
>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarn
ing', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'I
mportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryE
rror', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'R
untimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'System
Exit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'Unicod
eTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc_
_', '__name__', '__package__']

在linux下当我们按下ctrl c和ctrl d的时候,分别对应的是KeyboardInterruptEOFError的异常
如果存在多个异常,可以设置多个异常,多个异常可以放在同一个块内,也可以每个单独定义,这取决于你对异常的处理方式是否一致
except AssertionError:
XXXX
except AssertionError:
XXXX
或者
except (AssertionError,AssertionError):
XXXX
 
 
捕捉异常的时候可以访问异常的对象本身,可以记录下错误,使用,e提供一个元组,例如
[root@python ~]# cat 2.py
#!/usr/bin/env python
 
try:
x=input('first number:')
y=input('second number:')
print x/y
except (ZeroDivisionError,KeyboardInterrupt), e:
print e
[root@python ~]# ./2.py
first number:14
second number:0
integer division or modulo by zero
上面就记录了具体的错误信息integer division or modulo by zero.
程序的异常你可能无法完全捕获到,那么你可以使用except:后不接异常信息,捕获全部异常:
try:
x=input('first number:')
y=input('second number:')
print x/y
except:
print 'something wrong'
对于捕获全部异常,也可以使用
except Exception,e:
print 'invalid value:', e
来打印出异常的具体的信息.
还可以使用else子句,当没有抛出异常的时候,会执行else块的内容
#!/usr/bin/env python
while True:
try:
x=input('first number:')
y=input('second number:')
print x/y
except:
print 'something wrong'
else:
print 'well done'
break
上面的循环,当我们抛出异常的时候会重复执行,只有当我们输入正确的时候,才会调用else语句跳出循环:
[root@python ~]# ./test.py
first number:14
second number:0
something wrong
first number:14
second number:2
7
well done
可以使用finally子句,finally和else不同的是else只有在不抛出异常的时候才执行,而finally是无论如何都会执行.
finally:
print 'ok'







0 0