Python Try Except
The try
block lets you test a block of code for errors.
The except
block lets you handle the error.
The finally
block lets you execute code, regardless of the result of the try- and except blocks.
多种异常
您可以定义任意数量的异常块,例如,如果您想为特定类型的错误执行特殊的代码块
示例
如果 try 块引发 NameError
,则打印一条消息;如果引发其他错误,则打印另一条消息
try
print(x)
except NameError
print("变量 x 未定义")
except
print("Something else went wrong")
自己动手试一试 »