例外の引数にアクセスする
このステップでは、Python で例外に関連付けられた引数(args)にアクセスする方法を学びます。例外の引数は、発生したエラーに関するより具体的な詳細を提供することができます。
前のステップで作成した exceptions.py
ファイルを修正して、例外の引数にアクセスして出力するようにしましょう。VS Code エディタを使用して、~/project
ディレクトリ内の exceptions.py
を開きます。
## exceptions.py
def divide(x, y):
try:
result = x / y
print("The result is:", result)
except Exception as e:
print("An error occurred:", type(e), e.args)
divide(10, 2)
divide(10, 0)
divide("hello", 5)
このコードでは、except
ブロックを修正して e.args
を出力するようにしています。args
属性は、例外のコンストラクタに渡された引数を含むタプルです。
次に、exceptions.py
スクリプトを実行しましょう:
python exceptions.py
以下の出力が表示されるはずです:
The result is: 5.0
An error occurred: <class 'ZeroDivisionError'> ('division by zero',)
An error occurred: <class 'TypeError'> ("unsupported operand type(s) for /: 'str' and 'int'",)
ご覧のとおり、出力には各例外に関連付けられた引数が含まれています。ZeroDivisionError
の場合、引数は 'division by zero'
という文字列を含むタプルです。TypeError
の場合、引数は "unsupported operand type(s) for /: 'str' and 'int'"
という文字列を含むタプルです。
再度 exceptions.py
ファイルを修正して、最初の引数に直接アクセスするようにしましょう:
## exceptions.py
def divide(x, y):
try:
result = x / y
print("The result is:", result)
except Exception as e:
print("An error occurred:", type(e), e.args[0])
divide(10, 2)
divide(10, 0)
divide("hello", 5)
再度スクリプトを実行します:
python exceptions.py
以下の出力が表示されるはずです:
The result is: 5.0
An error occurred: <class 'ZeroDivisionError'> division by zero
An error occurred: <class 'TypeError'> unsupported operand type(s) for /: 'str' and 'int'
e.args[0]
にアクセスすることで、例外の最初の引数を抽出することができます。これは、エラーメッセージの中で最も説明的な部分であることが多いです。