Python except 关键字
定义和用法
The except
关键字用于 try...except 块。它定义了一个代码块,如果 try 块引发错误,则运行该代码块。
您可以为不同的错误类型定义不同的块,以及为没有错误时执行的块,请参阅下面的示例。
更多示例
示例
如果它是 NameError,则写一条消息,如果是 TypeError,则写另一条消息
x = "hello"
try
x > 3
except NameError
print("You have a variable that is not defined.")
except TypeError
print("You are comparing values of different type")
自己尝试 »
示例
尝试执行一个引发错误的语句,但没有定义的错误类型(在本例中为 ZeroDivisionError)
try
x = 1/0
except NameError
print("You have a variable that is not defined.")
except TypeError
print("You are comparing values of different type")
except
print("Something else went wrong")
自己尝试 »
示例
如果未引发任何错误,则写一条消息
x = 1
try
x > 10
except NameError
print("You have a variable that is not defined.")
except TypeError
print("You are comparing values of different type")
else
print("The 'Try' code was executed without raising any errors!")
自己尝试 »
相关页面
The try
关键字。
The finally
关键字。