例如:
如果该语句引发错误,则打印输出"Something went wrong":
try:
x > 3
except:
print("Something went wrong")
1、定义和用法
except
关键字在try... except块中使用。 如果try块引发错误,它将要运行定义的代码块。
可以为不同的错误类型定义不同的代码块,并在有问题的情况下执行对应的代码块,请参见下面的示例。
2、使用示例
例如:
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")
例如:
如果没有出现错误,使用else关键字打印输出信息:
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!")