异常处理
*try - except 语句 :
try:
检测范围
except Exception[as reason]:
出现异常(Exception)后的处理代码*
1.错误提示
f = open('我为什么是一个文件.txt')
print(f.read())
f.close
===================== RESTART: D:/Python/Mypython/test2.py =====================
Traceback (most recent call last):
File "D:/Python/Mypython/test2.py", line 1, in <module>
f = open('我为什么是一个文件.txt')
FileNotFoundError: [Errno 2] No such file or directory: '我为什么是一个文件.txt'
>>>
2.加上try语句,可以执行,提示错误
try:
f = open('我为什么是一个文件.txt')
print(f.read())
f.close
except OSError:
print('文件出错啦!')
===================== RESTART: D:/Python/Mypython/test2.py =====================
文件出错啦!
>>>
3.加上reason,提示错误的原因
try:
f = open('我为什么是一个文件.txt')
print(f.read())
f.close
except OSError as reason:
print('文件出错啦T_T\n错误的原因是:'+str(reason))
===================== RESTART: D:/Python/Mypython/test2.py =====================
文件出错啦T_T
错误的原因是:[Errno 2] No such file or directory: '我为什么是一个文件.txt'
>>>
4.可以添加多个异常,第一个出现异常输出,停止执行程序
try:
sum=1+'1'
f = open('我为什么是一个文件.txt')
print(f.read())
f.close
except OSError as reason:
print('文件出错啦T_T\n错误的原因是:'+str(reason))
except TypeError as reason:
print('类型出错啦T_T\n错误的原因是:'+str(reason))
===================== RESTART: D:/Python/Mypython/test2.py =====================
类型出错啦T_T
错误的原因是:unsupported operand type(s) for +: 'int' and 'str'
>>>
5.可以同时处理多个异常
try:
sum=1+'1'
f = open('我为什么是一个文件.txt')
print(f.read())
f.close
except (OSError,TypeError): ## 多个异常一起处理
print('出错啦T_T')
===================== RESTART: D:/Python/Mypython/test2.py =====================
出错啦T_T
>>>
*try - finally 语句 :
try:
检测范围
except Exception[as reason]:
出现异常(Exception)后的处理代码*
finally:
无论如何都会被执行的代码
raise语句(主动引起一个异常)
>>> 1/0
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
1/0
ZeroDivisionError: division by zero
>>> raise ZeroDivisionError
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
raise ZeroDivisionError
ZeroDivisionError
>>> raise ZeroDivisionError('除数为0的异常!')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
raise ZeroDivisionError('除数为0的异常!')
ZeroDivisionError: 除数为0的异常!
>>>
丰富的else 语句
1.当执行完while语句时,再执行else。若break了,则不执行else
while 条件:
执行语句1
break
else:
执行语句2
def showMaxFactor(num):
count=num//2 ## 整除,如11//2=5
while count>1:
if num%count==0:
print('%d最大的约数是:%d' %(num,count))
break ##若执行到break ,则不执行else
count-=1 ##若循环内容全部执行完没有路途跳出 ,则执行else
else:
print('%d是素数!'%num)
num=int(input('请输入一个整数:'))
showMaxFactor(num)
try --else
try:
int('abc') ## 出错,执行异常
except ValueError as reason:
print('出错啦:'+str(reason))
else:
print('没有任何异常!')
===================== RESTART: D:\Python\Mypython\新建文本文档.py ====================
出错啦:invalid literal for int() with base 10: 'abc'
>>> >`
try:
int('123') ## 未出错,执行else
except ValueError as reason:
print('出错啦:'+str(reason))
else:
print('没有任何异常!')
===================== RESTART: D:\Python\Mypython\新建文本文档.py ====================
没有任何异常!
>>>
with语句(自动调用f.close)
try:
with open('data.txt','w') as f:
for each_line in f:
print(each_line)
except OSError as reason:
print('出错啦:'+str(reason))
这篇博客主要介绍了Python的异常处理机制,包括try-except语句的使用,如何通过raise语句主动引发异常,详细的else子句功能,以及try-finally和with语句在自动资源管理中的应用。
494

被折叠的 条评论
为什么被折叠?



