How to raise exception in except block without original traceback in python 3.5+

Viewed 131

Library code can raise custom library exception; I would like to catch that one and raise my own exception without original exception and original traceback information attached:

    try:
        can_raise_custom_lib_exception()
    except custom_lib_exception as e:
        cleanup()
        raise myOwnException("my own extra text")

In this way original exception is thrown (with traceback), message:

During handling of the above exception, another exception occured:

is displayed followed by MyOwnException (with traceback).

Is it possible to hide original exception and display my exception only? It looks like python 3.5+ attaches the traceback information to the error and I would like to completely hide the first one.

1 Answers

Use raise from None to suppress earlier exceptions:

try:
    can_raise_custom_lib_exception()
except custom_lib_exception as e:
    cleanup()
    raise myOwnException("my own extra text") from None

7.8. The raise statement

[...]
Exception chaining can be explicitly suppressed by specifying None in the from clause:

Related