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

后端 未结 2 1675
北恋
北恋 2020-12-06 04:19

Consider

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


        
相关标签:
2条回答
  • 2020-12-06 04:47

    This can be done like this in Python 2.7 and 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...')
    
    0 讨论(0)
  • 2020-12-06 04:53

    In Python 3.3 and later raise ... from None may be used in this situation.

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

    This has the desired results.

    0 讨论(0)
提交回复
热议问题