Search code examples
pythontry-catchexcept

Possible to detect if I'm inside an 'except' clause in Python?


Ie, what I want would be:

try:
    print inExceptClause()
    1/0
except Exception:
    print inExceptClause()
print inExceptClause()

... which would print out:

False
True
False

Solution

  • I think you're going about this the wrong way. Your "use case" seems like that you can call a function from multiple points in your code, with it sometimes being called from within an exception handler. Within that function, you want to know whether or not an exception has been thrown, right?

    The point is, you don't want to have that kind of logic in a function that has (or should have) no knowledge about the calling code... as ideally, most of your functions will not have.

    That said, you might want to execute that function, but only partly. So I'd suggest one of two options:

    1. Split up the function into multiple functions: one function has extra functionality, and will in turn call the other function, that has reusable functionality. Just call the function you need, when you need it.

    2. Add a parameter to the function: a simple boolean value might be enough to in- or exclude a small part of that function.

    Now, this isn't really an answer to your question, but I have the feeling you are looking at your problem at the wrong angle... hence the above suggestion.