您可以使用 try.
您可以使用 except.
如果没有错误,可以使用 else.
无论块的结果如何 try 和 except,您仍然可以使用 finally.
如果发生错误或我们所说的异常,Python 通常会终止并生成错误消息。
语句 try 可用于处理某些异常。
示例:
会发生异常,因为未设置变量 x。
try:Without the try 程序吐出并停止。
print(x)
except:
print(Exception display here”)
try:
print(x)
except NameError:
print(变量 x 未定义”)
except:
print(发生错误”)
try:
print(Hello”)
except:
print(Error”)
else:
print(一切都很好”)
try:
print(Hello”)
except:
print(Error”)
finally:
print(在所有情况下运行”)
x=-2
if x <0:
引发 Exception(x 小于零”)
Please disable your ad blocker and refresh the window to use this website.