1、IOError
当打开一个不存在的文件时,此异常被抛出:
open("secret.log")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'secret.log'
在出现异常后,如果不捕获或者也不以其他任何方式进行处理,Python将立即停止运行程序,并显示栈追踪----异常发生前调用的函数清单。
2、引发异常
python内置函数和库函数通常在出现意外情况时引发异常,例如:
①整数除以0时将抛出异常,
10/0
随后抛出异常:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
②语法错误引发异常:
>>> a=====10
随后程序出现异常:
File "<stdin>", line 1
a=====10
^
SyntaxError: invalid syntax
③用raise主动抛出异常
>>> raise IOError("just for test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: just for test
可以使用try except来捕获多种异常
>>> try:
... int("summer")
... except (ValueError,TypeError):
... print("error !")
...
error !
>>>
可以使用多个except捕获异常:
>>> try:
... int("summer")
... except ValueError:
... print("value error")
... except TypeError:
... print("type error")
...
value error
捕获所有异常:
>>> try:
... int("summer")
... except Exception as e:
... print("error=%s"%e)
...
error=invalid literal for int() with base 10: 'summer'
清理操作:
在try/except 代码块中,可以包含执行清理操作的finally代码块,例如:
>>> try:
... int("summer")
... except TypeError:
... print("error")
... finally:
... print("finally do this")
...
finally do this
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'summer'