Gulzar
Gulzar

Reputation: 27936

catching all but specific exception in python

I have a code base with code like the following:

try:
    do_stuff()
except:
    print "yes, it's catching EVERYTHING"

Unfortunately, I don't have a quick enough way of knowing which types of exceptions can come, and am unable to let the system collapse upon encountering one.

This makes debugging hell.

I would like to make it easier upon myself by letting specific exceptions slip by - things like syntax errors, and others.

Is that possible? to catch everything BUT some specific exceptions?

thanks!

Upvotes: 2

Views: 72

Answers (1)

Tryph
Tryph

Reputation: 6209

you could do the following:

try:
    do_stuff()
except (SyntaxError, <any other exception>):
    raise  # simply raises the catched exception
except Exception:
    print "yes, it's catching EVERYTHING"

In addition, unless it is really what is wanted, except should never be used without exception specification since it will also catch KeyboardInterrupt and GeneratorExit. Exception should be specified at least; see the builtin exception hierarchy.


Note that, as @tobias_k stated in its below comment, the SyntaxError is detected before actually running the script, so it should not be needed to catch it.

For the challenge I looked for a way to actually catch a SyntaxError and the only case I found is the following (but there are other cases, see @brunodesthuilliers's comment):

try:
    eval(input('please enter some Python code: '))
except SyntaxError:
    print('oh yeah!')
$ python syntax_error.py
please enter some Python code: /
oh yeah!

My conclusion is that if you need to catch SyntaxError, this means your codebase does some stuffs even uglier than what you showed us... I wish you a lot of courage ;)

Upvotes: 4

Related Questions