sys.exc_info()

sys.exc_info()는 현재 스레드와 스택프레임에 해당하는 발생한 예외에 대한 정보를 반환한다. 반환값은 (type, value, traceback)으로 구성된 튜플이며 각 값의 의미는 정리하면 이와 같다.

  • 처리중인 exception type
  • exception type의 instance
  • 예외가 원래 발생한 지점에서 호출 스택을 캡슐화하는 traceback object이다.

 

다른 블로그를 참고하면 value에서는 에러 메시지를 얻을 수 있다고 한다.

import sys
 
# 예외를 발생시키는 함수 정의
def raise_exception():
    x = 1 / 0
 
try:
    raise_exception()
except:
    # 예외 정보 출력
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print(f"예외 타입: {exc_type}")
    print(f"예외 메시지: {exc_value}")
    print(f"예외 추적 정보: {exc_traceback}")
>> 출력결과
예외 타입: <class 'ZeroDivisionError'>
예외 메시지: division by zero
예외 추적 정보: <traceback object at 0x000001643504F040>

 

 

여기서 exc_value 변수의 타입을 확인하면 똑같이 ZeroDivisionError라는 예외 타입이 출력된다.

print(type(exc_value))
>> 출력
<class 'ZeroDivisionError'>

 

 

그렇지만 exc_type은 그저 type이고 값을 가지고 있는 객체가 아니기에 매직메소드에 접근하여 출력하면 값이 나오지 않지만, exc_value에 접근하여 __str__()메소드를 호출하여 값을 출력하면 값이 들어가있는 것을 확인할 수 있다.

print(exc_value.__str__())
>> 출력
division by zero
print(exc_type.__str__())
>> 출력
Traceback (most recent call last):
  File "c:\Users\USER\Desktop\Directory\Workspaces\PythonPractice\python_module\traceback\use_traceback.py", line 22, in <module>
    print(exc_type.__str__())
          ^^^^^^^^^^^^^^^^^^
TypeError: descriptor '__str__' of 'BaseException' object needs an argumen

 

 

dir()함수를 통한 exc_value와 exc_type의 attribute확인

>> 출력
exc_type의 dir() 함수 결과
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', 
'__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', 
'__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', 
'__suppress_context__', '__traceback__', 'add_note', 'args', 'with_traceback']

exc_value의 dir() 함수 결과
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', 
'__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', 
'__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', 
'__suppress_context__', '__traceback__', 'add_note', 'args', 'with_traceback']

attribute는 같은 클래스이므로 같은 것을 볼 수 있지만, 생성된 객체에서의 매직 메소드에 접근은 값이 출력될 수 있지만, 클래스 타입에서의 매직메소드는 가지고 있는 값이 없을 수 있기에 __str()__메소드에서 차이가 날 수 있다.

 

3.11 공식문서에는 이러한 내용이 있으니 참고할 필요도 있다.

버전 3.11에서 경: The type and traceback fields are now derived from the value (the exception instance), so when an exception is modified while it is being handled, the changes are reflected in the results of subsequent calls to exc_info().

  • exception instance에서 type과 traaceback filed가 모두 나온다고 한다.

 

 

 

참고자료

 

'Python 관련 > Python' 카테고리의 다른 글

[Python] traceback 사용법  (0) 2024.05.02