Python/ref keyword except

来自菜鸟教程
跳转至:导航、​搜索

<languages />

除关键字外的Python

❮Python关键字

如果该语句引发错误,则显示“出了点问题”:

    try:
  x > 3
except:
  print("Something went wrong")

定义和用法

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 关键词。

❮Python关键字