Python Try Except
- หน้าก่อนหน้า Python PIP
- หน้าต่อไป การบันทึกคำสั่ง Python
try
塊允許您測試代碼塊以查找錯誤。
except
塊允許您處理錯誤。
finally
塊允許您執行代碼,無論 try 和 except 塊的結果如何。
異常處理
當我們調用 Python 並發生錯誤或異常時,通常會停止並生成錯誤消息。
可以使用 try
語句處理這些異常:
ตัวอย่าง
try 块將生成異常,因為 x 未定義:
try: print(x) except: print("An exception occurred")
由於 try 块引發錯誤,因此會執行 except 块。
如果沒有 try 块,程序將崩潰並引發錯誤:
ตัวอย่าง
該語句將引發錯誤,因為未定義 x:
print(x)
多個異常
您可以根据需要定義任意數量的 exception 塊,例如,假如您要為特殊類型的錯誤執行特殊代碼塊:
ตัวอย่าง
如果 try 块引發 NameError
,則打印一條消息,如果是其他錯誤則打印另一條消息:
try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong")
Else
如果沒有引發錯誤,那麼您可以使用 else
關鍵字來定義要執行的代碼塊:
ตัวอย่าง
在本例中,try
塊不會生成任何錯誤:
try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong")
Finally
如果指定了 finally
块,則無論 try 块是否引發錯誤,都會執行 finally 块。
ตัวอย่าง
try: print(x) except: print("Something went wrong") finally: print("The 'try except' is finished")
นี่มีประโยชน์มากในการปิดโอบเจกต์และรีโซิว์ร์ซ์
ตัวอย่าง
พยายามเปิดและเขียนไฟล์ที่ไม่สามารถเขียนได้
try: f = open("demofile.txt") f.write("Lorum Ipsum") except: print("Something went wrong when writing to the file") finally: f.close()
โปรแกรมสามารถทำงานต่อไป และจะไม่เปิดโอบเจกต์ไฟล์
ลงทะเบียนข้อผิดพลาด
ในฐานะนักพัฒนา Python คุณสามารถเลือกที่จะลงทะเบียนข้อผิดพลาดเมื่อเกิดเงื่อนไข
ถ้าต้องการลงทะเบียน (ลงข้อผิดพลาด) ใช้ raise
คำถาม
ตัวอย่าง
ถ้า x ต่ำกว่า 0 จะลงทะเบียนข้อผิดพลาดและหยุดการปฏิบัติการ
x = -1 if x < 0: raise Exception("Sorry, no numbers below zero")
raise
คำถามใช้เพื่อลงทะเบียนข้อผิดพลาด
คุณสามารถกำหนดชนิดของข้อผิดพลาดที่จะลงทะเบียน และพิมพ์ข้อความให้กับผู้ใช้
ตัวอย่าง
ถ้า x ไม่ใช่ตัวเลข จะลงทะเบียน TypeError:
x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed")
- หน้าก่อนหน้า Python PIP
- หน้าต่อไป การบันทึกคำสั่ง Python