更多例子
如果是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!")
尝试一下