轻松上手,快乐学习!

Python 关键字 except


实例

如果该语句引发错误,则表示“Something went wrong"”:
try:
  x > 3
except:
  print("Something went wrong")
运行实例»

定义和用法

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!")
运行实例»

相关页面

try关键字。 finally关键字。