2

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!

0

1 Answer 1

4

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 ;)

Sign up to request clarification or add additional context in comments.

7 Comments

I think the SyntaxError is not even needed, as those should be detected before running the program, but otherwise, e.g. for special treatment of NameError, fine.
@tobias_k I finally found a way to catch a SyntaxError, see the edited answer ;)
@Tryph : other candidates for a SyntaxError (py2, I leave it to you to check the py3 changes): exec, execfile, compile, ast.literal_eval, ast.parse etc...
@Tryph oh and yes: you should definitly put the "except should never be used without exception specification" in bold (and even in blod caps as far as I'm concerned). I almost downvoted your post before seeing this part. FWIW, you should edit your example to actually NOT use a bare except ;-)
@brunodesthuilliers acknowledged
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.