快速体验
'''
需求:尝试以r模式打开文件,如果不存在,则以w模式打开
'''
try:
f= open ('test.txt','r')
except:
f = open('test,txt','w')
捕获指定异常
语法
try:
可能发生错误的代码
except:异常类型
如果捕获到该异常类型执行的代码
# 体验案例
# 需求:尝试执行大型num,如果名称错误就执行打印名称错误;
try:
print(num)
except NameError:
print('名称错误')
捕获多个制定异常
try:
print(1/0)
except Exception as result:#优势是不用程序员指定具体的异常类型
print(result)
捕获异常描述信息:Exception是所有程序异常的父类
try:
print(1/0)
except Exception as result:#优势是不用程序员指定具体的异常类型
print(result)
异常的else
else是指如果没有异常要执行的代码
try:
print(1)
except Exception as result1:
print(result1)
else:
print('执行这条代码说明没有异常')
异常的finally
finally表示的是无论是是否异常都要执行的代码,例如关闭文件。
try:
f = open('test.txt','r')
except Exception as result:
f = open('test.txt','w')
else:
print('没有异常')
finally:
f.close()