Paul Molodowitch
Paul Molodowitch

Reputation: 1446

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

Upvotes: 1

Views: 206

Answers (2)

Piotr Dobrogost
Piotr Dobrogost

Reputation: 42465

sys.exc_info()

This function returns a tuple of three values that give information about the exception that is currently being handled. (...) If no exception is being handled anywhere on the stack, a tuple containing three None values is returned.

See also these questions:

Python 3 traceback fails when no exception is active
Raising exceptions when an exception is already present in Python 3

Upvotes: 0

jro
jro

Reputation: 9484

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.

Upvotes: 3

Related Questions