2

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.

TDMNS
  • 281
  • 1
  • 6
  • 19
Ondrej
  • 817
  • 1
  • 9
  • 16

1 Answers1

2

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:

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119