异常

##异常
try:
1/0
except:
print("出错了")


出错了
try:
1/1
except:
print("出错了")


1.0
try:
1/0
except ZeroDivisionError as e:
print(e)


division by zero
try:
1/0
520+"fish"
except (ZeroDivisionError,ValueError,TypeError):
pass

try:
1/0
520+"fish"
except ZeroDivisionError:
print("除数不能为零")
except ValueError:
print("值不正确")
except TypeError:
print("类型不正确")


除数不能为零

try:
1/0
except:
print("逮到了")
else:
print("没逮到")


逮到了
try:
1/1
except:
print("逮到了")
else:
print("没逮到")


1.0
没逮到

#try-except-finally

try:
1/0
except:
print("逮到了")
else:
print("没逮到")
finally:
print("逮到了没逮到都说一声")


逮到了
逮到了没逮到都说一声
try:
f=open("fish","w")
f.write("I love fish")
except:
print("出错了")
finally:
print("晚安")


11
晚安

try:
try:
530+"hsah"
except:
print("内部异常")
1/0
except:
print("外部异常")
finally:
print("收尾工作")


内部异常
外部异常
收尾工作
try:
1/0
try:
520+"fish"
except:
print("内部异常")
except:
print("外部异常")
finally:
print("收尾工作")


外部异常
收尾工作

#raise语句
try:
1/0
except:
raise ValueError("值不正确")

Traceback (most recent call last):
File "<pyshell#81>", line 2, in <module>
1/0
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<pyshell#81>", line 4, in <module>
raise ValueError("值不正确")
ValueError: 值不正确

#assert语句
s="fish"
assert s=="fish"
assert s!="fish"
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
assert s!="fish"
AssertionError

try:
while True:
while True:
for i in range(10):
if i>3:
raise
print(i)
print("被跳过")
print("被跳过")
print("被跳过")
except:
print("到这来了")


0
1
2
3
到这来了

posted @   奋斗吧-少年  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示