錯誤導論

Intermediate Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

什麼是錯誤?

  • 違反規則的程式碼
  • 錯誤 = 例外(Exception)
  • 會讓程式終止!

部分 Python 例外的階層

1 https://docs.python.org/3/library/exceptions.html#exception-hierarchy
Intermediate Python for Developers

TypeError

  • 不相容的資料型別
"Hello" + 5

TypeError 輸出,顯示字串與整數不可相加

Intermediate Python for Developers

ValueError

float("Hello")

ValueError 輸出,說明字串 'Hello' 無法轉成 float

  • 值不在可接受範圍內
float("2")

輸出顯示結果 2.0,未發生錯誤

Intermediate Python for Developers

Tracebacks(錯誤追蹤)

追蹤訊息(Traceback)

Intermediate Python for Developers

Tracebacks(錯誤追蹤)

追蹤訊息,標示錯誤型別

Intermediate Python for Developers

Tracebacks(錯誤追蹤)

追蹤訊息,標示導致錯誤的程式碼

Intermediate Python for Developers

套件中的程式碼

  • 套件包含他人的程式碼,例如自訂函式
  • 稱為原始碼
  • pip install <package> 會將原始碼下載到本機環境
  • pandas 的 pd.read_csv() 會在背後執行該自訂函式所寫的程式碼
Intermediate Python for Developers

套件產生的 Tracebacks

# Import pandas package
import pandas as pd

# Create pandas DataFrame                 
products = pd.DataFrame({"ID": "ABC1",
                        "price": 29.99})

# Try to access the non-existent "tag" column
products["tag"]
Intermediate Python for Developers

套件產生的 Tracebacks

當嘗試以不存在的欄位篩選 pandas DataFrame 時的追蹤訊息

Intermediate Python for Developers

套件產生的 Tracebacks

追蹤訊息顯示執行時出錯的檔案,以及錯誤型別 KeyError

Intermediate Python for Developers

套件產生的 Tracebacks

追蹤訊息,標示第 3803 行

Intermediate Python for Developers

套件產生的 Tracebacks

追蹤訊息,標示 base.py

Intermediate Python for Developers

套件產生的 Tracebacks

追蹤訊息,標示 KeyError

Intermediate Python for Developers

套件產生的 Tracebacks

追蹤訊息顯示在我們程式碼中導致錯誤的那一行

Intermediate Python for Developers

套件產生的 Tracebacks

追蹤訊息顯示刻意丟出錯誤的程式碼

Intermediate Python for Developers

套件產生的 Tracebacks

追蹤訊息,標示 Raised

Intermediate Python for Developers

一起來練習吧!

Intermediate Python for Developers

Preparing Video For Download...