728x90
728x90

try-except 문 사용할 때 에러 발생 시, 전체 에러 정보 표시 방법

들어가며

  • try-except 문을 사용할 때, 에러를 표시하고 싶을 때가 있다.
  • 다음과 같이 에러를 표시할 경우, 에러 정보 중 1줄 정도만 짧게 출력된다.
  • 이때 1줄이 아닌, 여러 줄의 모든 에러 정보가 표시되도록 하는 방법을 정리해본다.
try:
print(1 / 0)
except Exception as e:
print(e)
division by zero

 

 

방법

traceback 모듈 사용하기

  • traceback 모듈을 import하여 try-except 문의 예외 처리 부분에 다음과 같이 넣어주면 된다.
import traceback
try:
print(1 / 0)
except Exception as e:
print(e)
traceback.print_exc() # 전체 오류 내역 출력하기
[ERROR] An exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

 

참고 사이트

 

traceback — Print or retrieve a stack traceback

Source code: Lib/traceback.py This module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when i...

docs.python.org

 

728x90
728x90

try-except 문 사용할 때 에러 발생 시, 전체 에러 정보 표시 방법들어가며방법traceback 모듈 사용하기참고 사이트