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

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


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

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

This has the desired results.


This can be done like this in Python 2.7 and Python 3:

try:    import someProprietaryModuleexcept ImportError as e:    raised_error = eif isinstance(raised_error, ImportError):    raise ImportError('It appears that <someProprietaryModule> is not installed...')


You can try logging module as well

import loggingtry:    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...')

gives

WARNING:root:python3ERROR:root:It appears that <someProprietaryModule> is not installed...[Program finished]