エラー処理

開発者向け中級 Python

Jasmin Ludolf

Senior Data Science Content Developer

Pandasのトレースバック

エラーを意図的に返すコードを示すトレースバック

  • except, raise

  • 起こりうるエラーを想定

開発者向け中級 Python

デザイン思考

  • カスタム関数はどのように使用されるか?
  • さまざまな使い方をテスト
  • 起こりうるエラーを特定

都市でのさまざまな通勤手段

開発者向け中級 Python

カスタム関数におけるエラー処理

def average(values):
    # Calculate the average
    average_value = sum(values) / len(values)
    return average_value
開発者向け中級 Python

間違える可能性のある場所

  • average():listまたはsetを想定
  • 2つ以上の引数を渡すのは不可 🛑
  • 誤ったデータ型は使用不可 🛑
開発者向け中級 Python

間違える可能性のある場所

sales_dict = {"cust_id": ["JL93", "MT12", "IY64"],
              "order_value": [43.21, 68.70, 82.19]}
print(average(sales_dict))

TypeError を含むトレースバック

開発者向け中級 Python

前回のエラー処理

  • 制御フロー ifelifelse
  • docstrings
開発者向け中級 Python

try-except

def average(values):

try:
# Code that might cause an error average_value = sum(values) / len(values) return average_value
except:
# Code to run if an error occurs print("average() accepts a list or set. Please provide a correct data type.")
開発者向け中級 Python

raise

def average(values):
    # Check data type
    if type(values) in (list, set):

# Run if appropriate data type was used average_value = sum(values) / len(values) return average_value
開発者向け中級 Python

raise

def average(values):
    # Check data type
    if type(values) in (list, set):

# Run if appropriate data type was used average_value = sum(values) / len(values) return average_value
else: # Run if an Exception occurs raise
開発者向け中級 Python

TypeErrorを発生させる

def average(values):
    # Check data type
    if type(values) in (list, set):

# Run if appropriate data type was used average_value = sum(values) / len(values) return average_value
else: # Run if an Exception occurs raise TypeError("average() accepts a list or set, please provide a correct data type.")
開発者向け中級 Python

TypeErrorを発生させる出力

print(average(sales_dict))

TypeErrorの出力。正しいデータ型を指定するカスタムメッセージを表示

開発者向け中級 Python

try-except vs. raise

try-except

  • エラーの発生を回避
  • それでも後続のコードを実行

raise

  • エラーを発生させる
  • 後続のコードの実行は実行しない
開発者向け中級 Python

練習しましょう!

開発者向け中級 Python

Preparing Video For Download...