Python except 关键字



  • 定义和用法

    except 关键字在try......except块使用。如果try块引发错误,它将定义要运行的代码块。您可以为不同的错误类型定义不同的块,并在没有问题的情况下执行块,请参见下面的示例。
  • 实例

    如果该语句引发错误,则显示“Something went wrong”:
    try:
      x > 3
    except:
      print("Something went wrong")
    
    
    尝试一下
  • 更多例子

    如果是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!")      
    
    
    尝试一下
  • 相关页面

    Python 教程:Python if...eles