Earlier today, I saw two different StackOverflow questions that basically looked like this:
Why does this not work? 
    try:
        [broken code]
    except:
        print('[-] exception occurred')
Unless someone can read minds or gets lucky or puts a whole lot more work into your question than you have any right to expect, the only answer anyone can give is "because an exception occurred", because your code goes out of its way to make it impossible for you to tell us what exception occurred and why.

This is exactly why you almost never want to handle exceptions with a bare except clause.

So, how do you want to handle exceptions?

If there's a specific exception you want to deal with, handle that

On both posts, someone suggested replacing the except: with except Exception:. But this doesn't really help anything.

OK, yes, it means that you'll no longer catch things like KeyboardInterrupt, which is nice, but it's still not going to help you tell what actually went wrong.

For example, one of the users' broken code was trying to create a socket, but he had a simple typo. Presumably he wanted to handle socket errors in some way, but because he used a bare except, the NameError raised by the typo looked exactly like a socket error. Handling Exception instead of everything wouldn't help that at all; socket.error and NameError are both subclasses of Exception. What you want to do here is handle socket.error.

    try:
        sock = socket(AF_INET, SOCK_STEAM)
    except socket.error:
        print('[-] exception occurred')

This way,  you'll get a traceback telling you there's a NameError on SOCK_STEAM, which is pretty easy to debug.

Sometimes, Exception is the right thing to handle (especially if you want to catch all unexpected exceptions at the very top of your program to log or display them in some way), but usually not.

Almost always use an as clause

Even just handling any Exception would still have allowed the user to debug his problem, if he hadn't thrown away all the information:
    try:
        sock = socket(AF_INET, SOCK_STEAM)
    except Exception as e:
        print('[-] exception occurred: {!r}'.format(e))
This doesn't give you a full traceback, or exit the program, but at least it lets you see NameError("name 'SOCK_STEAM' is not defined"), which is enough to debug the problem.

(If you really need to handle absolutely everything, even things like KeyboardInterrupt that aren't subclasses of Exception, how do you do that? You can't use an as clause with a bare except. But in recent Python—which includes 2.6 and 2.7, not just 3.x—"except BaseException:" does the same thing as "except:", so you write "except BaseException as e:". In earlier versions, you have to call sys.exc_info() to recover the exception.)

The one exception to this is in cases where there's only one thing that could go wrong, and the details of how it went wrong are irrelevant. That isn't actually true in this case—you'd like the log to tell you whether the socket failed because you're out of resources, or don't have permissions, or whatever, not just that it failed. But here are some examples where it's perfectly fine:

    try:
        import xml.etree.cElementTree as ET
    except ImportError:
        import xml.etree.ElemnetTree as ET

    try:
        return main[key]
    except KeyError:
        return backup[key]
(The second one could be handled better by a ChainMap, but let's ignore that; if you do want to do it with try/except, there's no reason to care about the information in the KeyError.)

If you can't handle the exception in some useful way, don't handle it

In the socket example, there's no point handling the error and just continuing on. The very next line of code is almost certainly going to be calling sock.bind or sock.connect, which will just raise a NameError anyway. If the socket creation fails, the whole function has presumably failed, so let the exception propagate back to the caller.

In general, it's your high-level functions that can do something useful with errors, not your mid-level functions (except maybe to reraise them with more context).

A start_server function had better either start the server, or report that it failed to do so in some way; it shouldn't return successfully with the server not running. And the obvious way to report that failure is to raise an exception. So, just let that socket call raise right through start_server.

At a higher level, you're going to have a daemon script or a GUI app or something else. That something else may want to wait 10 seconds and try again, or sys.exit(17), or popup up an error message and re-enable the "Start" button, or whatever. That higher-level function is where you want to handle the exception.

That may mean don't handle it at all

In fact, in many cases—especially early in development—the right place to handle an exception is nowhere at all. Just let the program exit and print a complete traceback that tells you (or, if not you, the people trying to help you on StackOverflow) exactly what you did wrong and where.

You might object that this is a bad end-user experience, but surely printing "[-] exception occurred" and then exiting (or printing out an endless stream of such messages and doing nothing useful) is just as bad of an end-user experience.

Once you have something working, it's often worth wrapping a top-level except Exception as e: at the top level to handle anything that escaped your design, because you want your server to log useful information somewhere and return an appropriate exit code, or you want to display the error in a window with instructions to submit a bug report instead of dumping it to the (possibly-non-existent) console. But until you've got things working at least far enough to do that, it's way too early to be catching everything anywhere.

Sidebar on other languages

Pretty much everything above applies to other languages that use exceptions, not just Python. But there's one more issue that comes up in a few languages, like C++, where you're often using a whole bunch of functions written for C that use status codes instead of exceptions.

In those cases, never call those C functions directly from your mid-level code. Instead, write code that wraps those calls up to raise exceptions when they fail, then use those functions from your mid-level code. (This is especially important if you're using RAII to manage resources, as you really should be in C++.)

This gives you a very simple rule of thumb: Your bottom-level code throws exceptions, your mid-level code just lets exceptions pass through, and your top-level code catches exceptions. That's not universally true, but it's true often enough to be a handy guide.
2

View comments

Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.