An Undesirable Consequence of Handling All Exceptions in Python
New programmers are often confused about the topic of exception handling and look for best practices in adopting exception handling into their existing code but without proper knowledge of how exception handling works under the hood it can cause their programs to behave unexpectedly.
In this article I will not go into details about the workings of exceptions but instead I will try to show an undesirable consequence of not specifying an exception class in your exceptional handling logic. I will work through the example starting with no exception handling initially and then gradually adding it to demonstrate a somewhat realistic thinking process as a programmer works through the program
Let’s begin with the example
This program tries to guess the user input. If the user input matches the random number generated from the randrange function, the program tells the user that he won and quits otherwise it keeps looping. Here’s the code
with no exception handling…
If you run this in your terminal and keep entering a few number inputs (< 10) you might win.
We can also terminate the running program by using CTRL-C as we do any other program
Ok, everything’s good so far.
Now lets try entering an invalid input this time and see what happens
We got a ValueError when we tried to enter a non-integer as the input. Ok, no problem lets try to handle that in the code
after adding broad exception handling…
There we have it our first exception handling attempt where we try to catch all exceptions blindly by not specifying any exception class. Lets see what happens
We don’t see the ValueError anymore with non-integer input so thats good but look what happens when we try to terminate the program like we did previously using CTRL-C. We can’t seem to??
By not specifying any exception class we seem to be catching all exceptions including KeyboardInterrupt exception. This is an undesirable consequence of not specifying an exception class. Let’s fix this
after specifying proper exception class…
then trying again
We seem to be catching the non-integer input and can still terminate the program using CTRL-C. We are all set now!
You should almost always specify an exception type in an except statement. Overly-broad exception handlers like the one demonstrated in this article will catch all exceptions that you don’t intend to catch