刻意练习Python DAY9

异常处理

1.AssertionError 断言语句(assert)失败

>>> list1=['小甲鱼']
>>> assert len(list1)>0
>>> list1.pop()
'小甲鱼'
>>> assert len(list1)>0
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    assert len(list1)>0
AssertionError

2.AttributeError 尝试访问未知的对象属性

>>> list1.fishc
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    list1.fishc
AttributeError: 'list' object has no attribute 'fishc'

3.IndexError 索引超出序列的范围

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

4.KeyError 字典中查找一个不存在的关键字

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

5.NameError 尝试访问一个不存在的变量

>>> fish
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    fish
NameError: name 'fish' is not defined

6.OSError 操作系统产生的异常(例如打开一个不存在的文件)
7.SyntaxError Python的语法错误
8.TypeError 不同类型间的无效操作
9.ZeroDivisionError 除数为零
10.异常检测
try:
检测范围
except Exception[as reason]:
出现异常(Exception)后的处理代码
finally:
无论如何都会被执行的代码

try:
    sum=1+'1'
    f=open('我是一个文件.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错啦!\n错误的原因是:'+str(reason))
except TypeError as reason:
     print('类型出错啦!\n错误的原因是:'+str(reason))
try:    
    f=open('我是一个文件.txt')
    print(f.read())
    sum=1+'1'
except(OSError,TypeError):
    print('出错啦!')
finally:
	f.close()

11.raise 引发异常

>>> raise
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    raise
RuntimeError: No active exception to reraise
>>> 1/0
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero
>>> raise ZeroDivisionError
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    raise ZeroDivisionError
ZeroDivisionError
>>> raise ZeroDivisionError('除数为零的异常')
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    raise ZeroDivisionError('除数为零的异常')
ZeroDivisionError: 除数为零的异常
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值