Bad idea to catch all exceptions in Python

Because it’s terribly nonspecific and it doesn’t enable you to do anything interesting with the exception. Moreover, if you’re catching every exception there could be loads of exceptions that are happening that you don’t even know are happening (which could cause your application to fail without you really knowing why). You should be able to predict (either through reading documentation or experimentation) specifically which exceptions you need to handle and how to handle them, but if you’re blindly suppressing all of them from the beginning you’ll never know.

So, by popular request, here’s an example. A programmer is writing Python code and she gets an IOError. Instead of investigating further, she decides to catch all exceptions:

def foo():
    try:
        f = open("file.txt")
        lines = f.readlines()
        return lines[0]
    except:
        return None

She doesn’t realize the issue in his ways: what if the file exists and is accessible, but it is empty? Then this code will raise an IndexError (since the list lines is empty). So she’ll spend hours wondering why she’s getting None back from this function when the file exists and isn’t locked without realizing something that would be obvious if she had been more specific in catching errors, which is that she’s accessing data that might not exist.

Leave a Comment