Gregory Nisbet Gregory Nisbet - 1 year ago 69
Python Question

Python determine whether an exception was thrown (regardless of whether it is caught or not)

I am writing tests for some legacy code that is littered with catch-all constructs like


for x in some_huge_list():

except Exception:

and I want to tell whether an exception was thrown inside the try block.

I want to avoid introducing changes into the codebase just to support a few tests and I don't want to make the
cases more specific for fear of unintentionally introducing regressions.

Is there a way of extracting information about exceptions that were raised and subsequently handled from the runtime? Or some function with a similar API to
that either records information on every raised exception, lets the user supply an exception handler that gets run first, or lets the user register a callback that gets run on events like an exception being raised or caught.

If there isn't a way to detect whether an exception was thrown without getting under the (C)Python runtime in a really nasty way, what are some good strategies for testing code with catch-all exceptions inside the units you're testing?

Answer Source

Your only realistic option is to instrument the except handlers.

Python does record exception information, which is retrievable with sys.exc_info(), but this information is cleared when a function exits (Python 2) or the try statement is done (Python 3).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download