AdSense

網頁

2025/6/12

Python 例外處理簡單範例

Python使用try except來處理例外錯誤(Errors and Exception)


範例

例如下面在get_val()函式的try區塊中引發IndexError錯誤,錯誤在except區塊中被捕捉並印出堆疊追蹤訊息,然後再拋出Exception,最後執行finally區塊。

get_val()拋出的Exception在其調用的try區塊被捕捉並於except區塊印出Exception的內容。

import traceback

def get_val(values, index):
    try:
        return values[index] # IndexError
    except IndexError as e:
        tb = traceback.format_exc() # get traceback
        print(tb)
        raise Exception("error: " + str(e))
    finally:
        print("finally")

values = [1, 2, 3, 4, 5]
try:
    v = get_val(values, 5)
    print(v)
except Exception as e:
    print(e)


測試

執行印出以下。

Traceback (most recent call last):
  File "c:\..\demo.py", line 5, in get_val
    return values[index] # IndexError
           ~~~~~~^^^^^^^
IndexError: list index out of range

finally
error: list index out of range

沒有留言:

AdSense