[Python] Error/Exception Processing (try statement; try-except)

try / except / else / finally

try:
  ...
except A:
  ...
except B as b:
  ...
else:
  ...
finally: # 必定被執行
  ...

Exception

BaseException 是由全部的例外所共用的 base class。

它的 subclass(子類別)之一,Exception
則是所有非嚴重例外 (non-fatal exception) 的 base class。

取得 exception e 的細節資訊

取得例外類別名稱

type(e).__name__

取得例外敘述、代碼…等

e.args 中, 是一個 tuple

str(e), repr(e)

參考 [Python] str(), repr()

取得發生例外的 檔案名/函數名/行號

traceback.format_exc()

traceback.format_exc()

sys.exc_info()

 

import sys, traceback

try: 
  ...
except Exception as e:
  cl, exc, tb = sys.exc_info() 
  # 傳回 type(e), e, e.__traceback__
  last_call_stack = traceback.extract_tb(tb)[0] 
  # 取得 tb 的 call stack 的第一筆資料
  file_name = last_call_stack[0] # 取得發生例外的檔案名
  func_name = last_call_stack[2] # 取得發生例外的函數名
  line_num = last_call_stack[1] # 取得發生例外的行號

 

raise

raise {exception[(args_0, args_1, ...)]}

Ref

https://docs.python.org/zh-tw/3/tutorial/errors.html

Last Updated on 2025/04/11 by A1go

目錄
Bitnami