简体   繁体   中英

In Python 2, How to raise a Python error without changing its traceback?

In the following typical try-except block:

try:
    do something
except Exception as e:
    {clean up resources}
    raise e
          ^

However, this will print out an error message with traceback pointing to ^, where the error is raised, in contrast to most other languages, where the traceback of e when it is first generated is remembered and printed instead.

The Python style of handling exception creates significant difficulty in figuring out the source of the error, and I would like to override it. Is there a simple way of doing this?

To catch an exception, do something with it and then re-raise the same exception:

try:
    do something
except Exception as e:
    {clean up resources}
    raise   # raises the same exception with the same traceback

To catch an exception, raise a new exception, but keep the old traceback:

try:
    do something
except Exception as e:
    exctype, value, traceback = sys.exc_info()
    raise NewException, 'Argument for new exception', traceback

This is described in Python 2.7 specification section 6.9 :

If no expressions are present, raise re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a TypeError exception is raised indicating that this is an error (if running under IDLE, a Queue.Empty exception is raised instead).

Otherwise, raise evaluates the expressions to get three objects, using None as the value of omitted expressions. The first two objects are used to determine the type and value of the exception.

...

If a third object is present and not None, it must be a traceback object (see section The standard type hierarchy), and it is substituted instead of the current location as the place where the exception occurred.

Python 3

Note that in Python 3, the original traceback is always preserved when raising from the except block. In other cases, syntax raise Exception() from another_exception is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM