python面向对象--异常处理

1.常见异常类型

IOError 文件读写异常
ValueError值异常,一般是数据类型不对应
IndexError下标索引越界

2.try...except...

try:
    f=open('test.txt')
except IOError as e:
    print(e)
>>:
[Errno 2] No such file or directory: 'test.txt'     

3.错误基类Exception

try:
    print(a)
except Exception as e:
    print(e)
>>:     
name 'a' is not defined     

4.else没发生异常就执行
5.finally无论如何都执行
6.raise主动触发异常

raise ImportError
>>:
*Traceback (most recent call last):
  File "D:/PycharmProjects/untitled2/test.py", line 9, in <module>
    raise ImportError
ImportError*