Python: A Beginner’s Guide to Basic Exception Handling

Eventually, you’re bound to develop a Python script that triggers an unforeseen occurrence (also referred to as a “runtime error”). If you fail to manage these occurrences appropriately, your script will collapse.

No matter how skilled a developer you are or will become, unforeseen circumstances arise that are beyond your control. You might write flawless code, but if it relies on user input, you may have no influence over whether they provide suitable input.

In essence, variables arise, and those variables do not always arise correctly.

That’s why Python incorporates exception handling. Without such handling, if a script does not execute as planned, you would be left clueless about what went amiss.

Allow me to illustrate with a blatant example.

We’re going to devise a Python script that will endeavor to divide 100 by 0. As basic math dictates, since 0 lacks a multiplicative inverse, division by zero is impossible.

Our Python script might appear something like this:

Upon running the above script, you’ll receive the error:

Unlike the ’80s tune by The Fixx, zero can’t save you in this scenario.

How do we circumvent this conundrum? Through exception handling.

In Python, you’ll encounter a myriad of exceptions. These exceptions are classified into base classes (like with_traceback, ArithmeticError, BufferError, and LookupError) and concrete exceptions (such as AssertionError, AttributeError, EOFError, ImportError, and ZeroDivisionError). You can delve further into the different types of errors in Python’s documentation on exception handling.

How to Manage Exceptions in Python

There are four primary types of exception handling in Python, namely:

  • Try: Attempt a block of code.
  • Except: Handle the error.
  • Else: If there is no exception in the code, this code will be executed.
  • Finally: This code will always be executed.

Today, we’ll focus on two of these: try and except.

The advantageous aspect of these exception handlers is that they can alert a user to incorrect input. Recall that we observed the ZeroDivisionError displayed in our prior exception output. You can actually encode that into your script with the except option in a way that notifies the user about their flawed input.

Allow me to demonstrate. We’ll stick with our division script, but it gets slightly more intricate because we’ll utilize the except and try functions along with the ZeroDivisionError concrete exception.

The initial line will be straightforward:

This indicates to Python to test the block of code that follows.

The subsequent lines will accept user input to define a and b, then display the result. However, thanks to try and except, Python discerns exactly what to do. Essentially, python will try the block of code and display the results unless the ZeroDivisionError exception error is encountered. In that case, it will notify the user that they cannot divide by zero. Create the script with the command:

Within that file, paste the following:

Save and close the file.

Execute the script with the command:

Input 90 for the first number and 0 for the second. The output will be:

Try again, and this time input 90 and 9. The output will be:

But what occurs if a user inputs a letter (or a word)? How do you manage that exception error? For that, we have ValueError, which can be integrated like so:

Add the above two lines to the end of your file and save/close it. Run the script again, and input 90 for the first value and a for the second. The output will be:

Exception as e

There’s another intriguing technique for exception handling that I want to mention, which is Exception as e. I’ll demonstrate this technique by utilizing it to evoke an IndexError when a list index exceeds its boundaries.

Let’s say, for instance, we create a list of four colors: