Python except 关键字

实例

如果语句引发错误,则打印 "Something went wrong":

  1. try:
  2. x > 3
  3. except:
  4. print("Something went wrong")

定义和用法

在 try … except 块中使用了关键字 except。它定义 try 块引发错误时要运行的代码块。

您可以为不同的错误类型定义不同的块,以及没有问题的情况下执行的块,请参见下面的例子。

更多实例

实例 1

如果引发 NameError 则写一条消息,如果引发 TypeError 则写另一条:

  1. x = "hello"
  2.  
  3. try:
  4. x > 3
  5. except NameError:
  6. print("You have a variable that is not defined.")
  7. except TypeError:
  8. print("You are comparing values of different type")

实例 2

尝试执行一条引发错误的语句,但没有定义的错误类型(在这种情况下为 ZeroDivisionError):

  1. try:
  2. x = 1/0
  3. except NameError:
  4. print("You have a variable that is not defined.")
  5. except TypeError:
  6. print("You are comparing values of different type")
  7. except:
  8. print("Something else went wrong")

实例 3

如果没有出现错误,写一条消息:

  1. x = 1
  2.  
  3. try:
  4. x > 10
  5. except NameError:
  6. print("You have a variable that is not defined.")
  7. except TypeError:
  8. print("You are comparing values of different type")
  9. else:
  10. print("The 'Try' code was executed without raising any errors!")

相关页面

try 关键字

finally 关键字