|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
L31异常处理
程序逻辑错误或者用户输入不合法都可能引起异常,这些异常不是致命的不会导致程序
崩溃死掉,可以利用python的异常处理机制将异常处理消化掉。
assert断言
当assert后边大于零的时候程序正常执行,否则抛出异常
>>> mylist=['xiaojiayu']
>>> assert len(mylist)>0
>>> mylist.pop()
'xiaojiayu'
>>> assert len(mylist)>0
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
assert len(mylist)>0
AssertionError
L33异常处理2
Try-except语句
try:
检测范围
Except Exception[as reason]:
出现异常(exception)后的处理代码
例子:
try:
f=open('why am I a file.txt')
print(f.read())
f.close()
except OSError as reason:
print('文件出错\n错误的原因是:'+str(reason))
一个try语句可以和多个except 语句搭配,分别对我们感兴趣的异常进行检测处理
try:
sum=1+'1'#typeerror
f=open('why am I a file.txt')
print(f.read())
f.close()
except OSError as reason:
print('文件出错\n错误的原因是:'+str(reason))
except TypeError as reason:
print('文件出错\n错误的原因是:'+str(reason))
如果try语句块的程序错误如果没有包含在except里面,则还会出现traceback的错误警告
将except 后边的东西都省略,但这样会隐藏所有程序员未准备好处理的异常和错误。不推荐这样做
try:
sum=1+'1'#typeerror
f=open('why am I a file.txt')
print(f.read())
f.close()
except:
print('error')
Ctrl +c #这里是使程序中断,但是这个异常也会被except捕获从而不被执行。
注意:try 语句块里的语句一旦出现异常剩下的语句将不会被执行。
同时捕获两个异常
try:
sum=1+'1'#typeerror
f=open('why am I a file.txt')
print(f.read())
f.close()
except(OSError,TypeError):
print('error')
Try-finally方式:
finally以后的语句是无论如何都会被执行的。
当程序出现错误后跳到except 语句,然后finally后的语句被执行。
如果程序无错误则跳过except语句,执行finally后的语句
Raise
代码本身引发一个异常
raise
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
raise
RuntimeError: No active exception to reraise
raise ZeroDivisionError
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
raise ZeroDivisionError
ZeroDivisionError
>>> raise ZeroDivisionError('除数为零的异常')#括号内对异常进行解释
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
raise ZeroDivisionError('除数为零的异常')
ZeroDivisionError: 除数为零的异常
|
评分
-
查看全部评分
|