python学习笔记异常(Exception)(七)

一常见异常

1.AssertionError

断言语句(assert)失败,示例如下:

>>> a = 1
>>> assert(a<1)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    assert(a<1)
AssertionError

2.IndexError

索引越界,导致索引错误

>>> list1 = [1,2,3]
>>> list1[3]
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    list1[3]
IndexError: list index out of range

3.keyError

引用字典中不存在的key

>>> dict1={'1':'one','2':'two','3':'three'}
>>> dict1['4']
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    dict1['4']
KeyError: '4'

4.TypeError

类型异常

>>> 1 + '1'
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    1 + '1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

5.ZeroDivisionError

0被当着被除数的错误

>>> 5/0
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    5/0
ZeroDivisionError: division by zero

二 捕获异常 try-catch

运行期检测到的错误被称为异常。为了防止异常出现导致程序中断,可增加异常处理try-catch语句块

try:
    检测范围
catch Except:
   出现异常(Exception)的代码处理

2.1文件不存在

2.1.1 当打开一个文件时,可能会出现文件不存在,示例代码如下:

f = open("nihao.txt")
print(f.read())
f.close()

===== RESTART: D:\sources\python\python\05exception_file.py ====
Traceback (most recent call last):
  File "D:\sources\python\pytho\05exception_file.py", line 1, in <module>
    f = open("nihao.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'nihao.txt'

2.1.2 对可能抛异常的代码块,添加try-catch语句块后,报错信息比较友好

try:
    f = open("nihao.txt")
    print(f.read())
    f.close()
except OSError:
    print('文件出错了')
>>> 
===== RESTART: D:\sources\python\python\05exception_file.py ====
文件出错了

2.1.3 抛出异常信息

try:
    f = open("nihao.txt")
    print(f.read())
    f.close()
except OSError as reason:
     print('文件出错了\n错误原因是:' + str(reason) )
===== RESTART: D:\sources\python\python\05exception_file.py ====
文件出错了
错误原因是:[Errno 2] No such file or directory: 'nihao.txt'

2.2 多个异常处理

多个异常的处理,当第二行报错时,直接跳转到第二个捕获异常的语句块

try:
    sum = 1 + '1'
    f = open("nihao.txt")
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错了\n错误原因是:' + str(reason) )
except TypeError as reason:
    print('类型错误',reason)
    
===== RESTART: D:\sources\python\python\05exception_file.py ====
类型错误 unsupported operand type(s) for +: 'int' and 'str'

另外一种写法

try:
    sum = 1 + '1'
    f = open("nihao.txt")
    print(f.read())
    f.close()
except(OSError,TypeError) as reason:
    print('出错了\n错误原因是:' + str(reason) )

-----------------------
===== RESTART: D:\sources\python\python\05exception_file.py ====
出错了
错误原因是:unsupported operand type(s) for +: 'int' and 'str'

try-finally

finally用于关闭文件,不加finally语句块,写入的‘你好啊’不会保存到文件中;示例如下

try:
    
    f = open("nihao.txt",'w')
    print(f.write('你好啊'))
    sum = 1 + '1'
    f.close()
except(OSError,TypeError) as reason:
    print('出错了\n错误原因是:' + str(reason) )
finally:
    f.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值