##异常
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
到这来了