Question

For a block like this:

try:
    #some stuff
except Exception:
    pass

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

Was it helpful?

Solution

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.

OTHER TIPS

It's good practice to catch only a very narrow range of types. 'Exception' is too general - you will end up catching not just the errors you planned for, but other errors too, which may mask bugs in your code that would be quicker to diagnose if they weren't caught at all, or possibly would be better dealt with by a single very high level exception handler.

Having said that, 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.

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

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.

like Greg's answer, 'Exception' is a base class and exceptions should be derived from this class, see also exceptions.Exception.

Here a very usefull list of Errors in pydocs

Note also the very handy traceback module which allows you to find out where the exception occured. Using only 'except: ...' will show you what Error you should best use in your case. For example, try this code (toggle the comment), perhaps you'll accept it:

import traceback
#absent = 'nothing'
try:
    something = absent
except  NameError:
    traceback.print_exc()
else:
    print("you get here only when you uncomment 'absent'") 

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top