当我在响应中提出自己的异常时,如何更容易地抑制先前的异常?

时间:2013-06-13 15:51:27

标签: python exception python-3.x python-3.3 traceback

考虑

try:
   import someProprietaryModule
except ImportError:
   raise ImportError('It appears that <someProprietaryModule> is not installed...')

运行时,如果未安装someProprietaryModule,则会看到:

(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...')

但这感觉有点像黑客。我还能做什么?

3 个答案:

答案 0 :(得分:36)

在Python 3.3及更高版本中raise ... from None可能会在这种情况下使用。

try:
   import someProprietaryModule
except ImportError:
   raise ImportError('It appears that <someProprietaryModule> is not installed...') from None

这会产生预期的效果。

答案 1 :(得分:1)

这可以在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...')

答案 2 :(得分:0)

您也可以尝试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]