Python except 关键字
实例
如果语句引发错误,则打印 "Something went wrong":
try: x > 3 except: print("Something went wrong")
定义和用法
在 try ... except 块中使用了关键字 except。它定义 try 块引发错误时要运行的代码块。
ကျွန်တော် အမှား အမျိုးမျိုး အတွက် အခုံ အမျိုးမျိုး ကို ဒေါ်လုပ် နိုင်ပါ၏၊ တော့ အမှား မရှိ သော အခါ လုပ်ဆောင် သည့် အခုံ ကို လည်း ဒေါ်လုပ် နိုင်ပါ၏၊ အောက်ပါ အကျယ်အဝန်း ကို ကျွန်တော် ကျယ်ပါသည်။
More examples
Example 1
If a NameError is raised, write a message, and if a TypeError is raised, write another message:
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")
Example 2
Try to execute a statement that raises an error, but do not define the error type (in this case 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")
Example 3
If no error occurs, write a message:
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!")