예외 args 접근
이 단계에서는 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]에 접근함으로써 예외의 첫 번째 인수를 추출할 수 있으며, 이는 종종 오류 메시지의 가장 설명적인 부분입니다.