[英]How to get the name of an exception that was caught in 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'
您也可以使用sys.exc_info()
。 exc_info()
返回 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:
foo = bar
except Exception as exception:
assert repr(exception) == '''NameError("name 'bar' is not defined",)'''
name = repr(exception).split('(')[0]
assert name == '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
您可以使用一些格式化的字符串打印異常:
例子:
try:
#Code to execute
except Exception as err:
print(f"{type(err).__name__} was raised: {err}")
這里的其他答案非常適合探索,但如果主要目標是記錄異常(包括異常的名稱),也許可以考慮使用logging.exception而不是打印?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.