반응형
Python에서 검출된 예외의 이름을 얻는 방법은 무엇입니까?
Python에서 발생한 예외의 이름을 얻으려면 어떻게 해야 합니까?
예.,
try:
foo = bar
except Exception as exception:
name_of_exception = ???
assert name_of_exception == 'NameError'
print "Failed with exception [%s]" % name_of_exception
예를 들어, 여러 (또는 모든) 예외를 포착하고 오류 메시지에 예외 이름을 인쇄하려고 합니다.
다음은 예외 클래스의 이름을 가져오는 몇 가지 다른 방법입니다.
type(exception).__name__
exception.__class__.__name__
exception.__class__.__qualname__
예.,
try:
foo = bar
except Exception as exception:
assert type(exception).__name__ == 'NameError'
assert exception.__class__.__name__ == 'NameError'
assert exception.__class__.__qualname__ == 'NameError'
완전 수식 클래스명을 필요로 하는 경우(예:sqlalchemy.exc.IntegrityError
뿐만 아니라IntegrityError
MB의 멋진 답변에서 가져온 다음 함수를 사용할 수 있습니다(기호에 맞게 변수 이름을 변경했습니다).
def get_full_class_name(obj):
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return obj.__class__.__name__
return module + '.' + obj.__class__.__name__
예를 들어:
try:
# <do something with sqlalchemy that angers the database>
except sqlalchemy.exc.SQLAlchemyError as e:
print(get_full_class_name(e))
# sqlalchemy.exc.IntegrityError
를 사용할 수도 있습니다.sys.exc_info()
.exc_info()
type, value, traceback의 3가지 값을 반환합니다.매뉴얼 : https://docs.python.org/3/library/sys.html#sys.exc_info
import sys
try:
foo = bar
except Exception:
exc_type, value, traceback = sys.exc_info()
assert exc_type.__name__ == 'NameError'
print "Failed with exception [%s]" % exc_type.__name__
다음과 같은 형식화된 문자열을 사용하여 예외를 인쇄할 수 있습니다.
예를 들어:
try:
#Code to execute
except Exception as err:
print(f"{type(err).__name__} was raised: {err}")
이게 먹히긴 하는데, 좀 더 쉽고 직접적인 방법이 있을 것 같은데요?
try:
foo = bar
except Exception as exception:
assert repr(exception) == '''NameError("name 'bar' is not defined",)'''
name = repr(exception).split('(')[0]
assert name == 'NameError'
여기 있는 다른 답변은 탐색을 위해 좋지만, 예외의 이름을 포함하여 예외를 기록하는 것이 주요 목표라면 인쇄 대신 logging.exception을 사용하는 것을 고려해 주십시오.
언급URL : https://stackoverflow.com/questions/18176602/how-to-get-the-name-of-an-exception-that-was-caught-in-python
반응형
'source' 카테고리의 다른 글
backbone.js의 목적은 무엇입니까? (0) | 2022.11.04 |
---|---|
임베디드 객체 속성별로 스프링 데이터 JPA 찾기 (0) | 2022.11.04 |
HashSet과 Set의 차이점은 무엇입니까? (0) | 2022.11.04 |
C 코드를 작성하여 직사각형의 면적을 계산합니다.calculate라는 이름의 단일 함수를 사용하여 면적을 계산합니다. (0) | 2022.11.04 |
비활성화/활성화 버튼의 경우 VueJs v-if (0) | 2022.11.04 |