Python全系列 教程
3567个小节阅读:5929.7k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
try...except...finally
结构中,finally
块无论是否发生异常都会被执行;通常用来释放try
块中申请的资源。
【示例】try...except...finally
结构简单测试
xxxxxxxxxx
try:
a = input("请输入一个被除数:")
b = input("请输入一个除数:")
c = float(a)/float(b)
except BaseException as e:
print(e)
else:
print(c)
finally:
print("我是finally中的语句,无论发生异常与否,都执行!")
print("程序结束!")
执行结果如下:
xxxxxxxxxx
请输入被除数:10
请输入除数:0
float division by zero
我是finally中的语句,无论是否发生异常都执行
【示例】读取文件,finally
中保证关闭文件资源
xxxxxxxxxx
try:
f = open("d:/a.txt",'r')
content = f.readline()
print(content)
except BaseException as e:
print(e)
finally:
f.close() #释放资源。此处也可能会发生异常。若发生异常,则程序终止,不会继续往下执行
print("step4")
发生异常的执行结果:
xxxxxxxxxx
Traceback (most recent call last):
[Errno 2] No such file or directory: 'd:/a.txt'
File "...mypro_exception/my01.py", line 8, in <module>
f.close() #释放资源。此处也可能会发生异常。若发生异常,则程序终止,不会继续往下执行
NameError: name 'f' is not defined
Process finished with exit code 1
由于return
有两种作用:结束方法运行、返回值。我们一般不把return
放到异常处理结构中,而是放到方法最后。
【示例】return
和异常结构的正确处理方式
xxxxxxxxxx
def test01():
print("step1")
try:
x = 3/0
# return "a"
except:
print("step2")
print("异常:0不能做除数")
#return "b"
finally:
print("step4")
#return "d"
print("step5")
return "e" #一般不要将return语句放到try、except、else、finally块中,会发生一些意想不到的错误。建议放到方法最后。
print(test01())
执行结果:
xxxxxxxxxx
step1
step2
异常:0不能做除数
step4
step5
e
实时效果反馈
1. 如下关于异常机制的代码,执行结果正确的是:
xxxxxxxxxx
try:
c = 3/0
print("step1")
except BaseException as e:
print("step2")
else:
print("step3")
finally:
print("step4")
print("step5")
A step1 step2 step4 step5
B step2 step4 step5
C step1 step3 step4 step5
D step1 step2 step4
答案
1=>B