考虑
try:
import someProprietaryModule
except ImportError:
raise ImportError('It appears that <someProprietaryModule> is not installed...')
运行时,如果未安装某些专有模块,则会看到:
(traceback data)
ImportError: unknown module: someProprietaryModule
During handling of the above exception, another exception occurred:
(traceback data)
ImportError: It appears that <someProprietaryModule> is not installed...
也许我不希望出现“在处理上述异常期间...”行(及其上面的行)。我可以这样做:
_moduleInstalled = True
try:
import someProprietaryModule
except ImportError:
_moduleInstalled = False
if not _moduleInstalled:
raise ImportError('It appears that <someProprietaryModule> is not installed...')
但这感觉有点像黑客。我还能做什么?
在Python 3.3及更高版本中
raise ... from None
可以在这种情况下使用。
try:
import someProprietaryModule
except ImportError:
raise ImportError('It appears that <someProprietaryModule> is not installed...') from None
这已经达到了预期的结果。
这可以在 Python 2.7 和 Python 3 中这样完成:
try:
import someProprietaryModule
except ImportError as e:
raised_error = e
if isinstance(raised_error, ImportError):
raise ImportError('It appears that <someProprietaryModule> is not installed...')
您也可以尝试
logging
模块
原答案: 也许我不希望出现“在处理上述异常期间...”行(及其上面的行)。
import logging
try:
import someProprietaryModule
except Exception as e:
if hasattr(e, 'message'):
logging.warning('python2')
logging.error(e.message)
else:
logging.warning('python3')
logging.error('It appears that <someProprietaryModule> is not installed...')
给予
WARNING:root:python3
ERROR:root:It appears that <someProprietaryModule> is not installed...
[Program finished]
编辑:
import logging
class MyExceptionType(Exception):
"""Base class for other exceptions"""
pass
try:
from someProprietaryModule import *
except Exception as e:
logging.warning('python3')
logging.exception("Failed to import <someProprietaryModule>. Is it installed?", exc_info=False)
raise MyExceptionType from e
logging.exception
将发出堆栈跟踪以及本地化错误消息,这使得它非常有用。
将异常转换为字符串来打印它会删除 90% 的有用信息。
默默地抑制异常几乎总是一个错误,而且最常见的是枪炮。
编辑2:
import logging
class MyExceptionType(Exception):
"""Base class for other exceptions"""
pass
try:
import someProprietaryModule
except Exception as e:
error_message = "Failed to import <someProprietaryModule>. Is it installed?"
logging.warning('python3')
logging.error(error_message, exc_info=True) # Log the stacktrace along with the message
raise MyExceptionType(error_message) from e
logging.error 调用中的 exc_info 参数设置为 True,允许日志记录模块在日志输出中包含异常信息,包括回溯。 本地化的错误消息存储在变量 error_message 中,这使得代码更具可读性,并且可以在需要时轻松更改。