tags:

views:

494

answers:

5

For a block like this:

try:
    #some stuff
except Exception:
    pass

pylint raises warning W0703 'Catch "Exception"'. Why?

+9  A: 

It's considered good practice to not normally catch the root Exception object, but instead to catch more specific ones - for example IOException.

Consider if an out of memory exception occurred - simply using "pass" isn't going to leave your programme in a good state.

Pretty much the only time you should catch Exception is at the top level of your programme, where you can (try to) log it, display an error, and exit as gracefully as you can.

Greg
+4  A: 

because it thinks that you're catching too much. and it's right.

SilentGhost
+1  A: 

Exception are raised when something... exceptional occurs. It's generally a good thing that the program terminates.

You may want to ignore some exceptions, but IMO there's no good reason for catching a base-class like that.

Bastien Léonard
Hey. I don't think I agree that 'there is no good reason' - I can imagine, for example, a GUI program that raises an exception when attempting a particular operation on a particularly tricky data set. It's all well and good as a programmer to say that an unexpected exception should end the program with a stack trace (fail early), but in practice what the user wants is for the current operation to fail gracefully, maybe with a messagebox or logfile message, and then for the GUI to continue operating so that they can e.g. save their data before anything else bad happens.
Tartley
I totally agree, I was refering to the way the OP ignores exceptions with `pass`. I should have made my point more clear.
Bastien Léonard
Beg your pardon, fair enough then.
Tartley
A: 

Catching Exception (without re-raising) has 2 really bad side effects: errors get eaten, so you lose the stack trace, but also that ctrl-c (or whatever the break key is on your operating system) also gets handled here.

The typical behavior of programs like this is that either they can't be stopped, or that ctrl-c causes the control flow to skip forward (to the exception handler), and then continue. Then either the code can't be interrupted, or you need to hammer on ctrl-c to get it to stop.

Paul Hankin
This is no longer true from Python 2.6, KeyboardInterrupt no longer inherits from Exception.
Tartley
+7  A: 

Since Python2.6 catching Exception has become a lot more reasonable, because all the exceptions that you wouldn't want to catch (SystemExit, KeyboardInterrupt) no longer inherit from Exception. They instead inherit from a common BaseException instead. This has been done deliberately in order to make catching Exception relatively harmless, since it is such a common idiom.

See PEP 3110 for details & future plans.

Tartley