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

How can I more easily suppress previous exceptions when I raise my own exception in response?

考虑

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

运行时,如果没有安装某个专有模块,可以看到:

1
2
3
4
5
6
7
(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...

也许我不希望"在处理上面的异常期间……"行(以及上面的行)出现。我可以这样做:

1
2
3
4
5
6
7
_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

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

这就得到了预期的结果。


这可以在python2.7和python3中这样做:

1
2
3
4
5
6
7
try:
    import someProprietaryModule
except ImportError as e:
    raised_error = e

if isinstance(raised_error, ImportError):
    raise ImportError('It appears that <someProprietaryModule> is not installed...')