Join our community of software engineering leaders and aspirational developers. Always
stay in-the-know by getting the most important news and exclusive content delivered
fresh to your inbox to learn more about at-scale software development.
REQUIRED
It seems that you've previously unsubscribed from our newsletter
in the past. Click the button below to open the re-subscribe form
in a new tab. When you're done, simply close that tab and continue
with this form to complete your subscription.
The New Stack does not sell your information or share it with
unaffiliated third parties. By continuing, you agree to our
Terms of Use and
Privacy Policy.
Welcome and thank you for joining The New Stack community!
Please answer a few simple questions to help us deliver the news and resources you are interested in.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Great to meet you!
Tell us a bit about your job so we can cover the topics you find most relevant.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Welcome!
We’re so glad you’re here. You can expect all the best TNS content to arrive
Monday through Friday to keep you on top of the news and at the top of your game.
What’s next?
Check your inbox for a confirmation email where you can adjust your preferences
and even join additional groups.
Follow TNS on your favorite social media networks.
At some point, you’re going to create a Python program that generates an unexpected event (also known as a “runtime error”). If you don’t handle these events properly, your program will fail.
No matter how good a programmer you are or will be, things happen that are out of your control. You could write the perfect code, but if it depends on user input, you might not have any say on whether they input something that works.
In other words, variables happen, and those variables don’t always happen properly.
That’s why Python includes exception handling. Without such handling, if a program does not run as intended, you would be left clueless as to what went wrong.
Let me show you a very obvious example.
We’re going to create a Python program that will attempt to divide 100 by 0. If you can recall basic math, because 0 has no multiplication inverse, you can’t divide by zero.
Our Python program might look something like this:
a = 100
b = 0
print (a/b)
If you run the above program, you’ll get the error:
Traceback (most recent call last):
File "/home/jack/exception.py", line 3, in <module>
print (a/b)
~^~
ZeroDivisionError: division by zero
Unlike in the ’80s song by The Fixx, you can’t be saved by zero in this case.
How do we get around this issue? With exception handling.
In Python, you’ll find quite a large number of exceptions. These exceptions are categorized into base classes (such as with_traceback, ArithmeticError, BufferError and LookupError) and concrete exceptions (such as AssertionError, AttributeError, EOFError, ImportError and ZeroDivisionError). You can read more about the different kinds of errors in Python’s documentation on exception handling.
How to Handle Exceptions in Python
There are four primary types of exception handling in Python, which are:
Try: Try a piece 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’re going to look at two of these: try and except.
The nice thing about these exception handlers is that they can warn a user they’ve used incorrect input. You’ll recall that we saw the ZeroDivisionError displayed in our previous exception output. You can actually code that into your program with the except option in such a way that it will warn the user they have used incorrect input.
Let me demonstrate. We’re going to stick with our division program but it gets a bit more complicated because we’re going to employ the except and try functions along with the ZeroDivisionError concrete exception.
The first line will be simply:
try:
This informs Python to try the block of code the follows.
The next few lines will accept user input to define a and b and then print the result. However, because we’re using try and except, Python knows exactly what to do. Essentially, python will try the block of code and print the results unless the ZeroDivisionError exception error isn’t discovered. If the error is discovered, it will inform the user that they cannot divide by zero. Create the program with the command:
nano exception.py
In that file, paste the following:
try:
a = int(input("Type a number: "))
b = int(input("Type another number: "))
result = a / b
print(result)
except ZeroDivisionError:
print("You cannot divide by zero.")
Save and close the file.
Run the program with the command:
python3 exception3.py
Input 90 for the first number and 0 for the second. The output will then be:
You cannot divide by zero.
Try again, only this time enter 90 and 9. The output will be:
10.0
But what happens if a user inputs a letter (or a word)? How do you handle that exception error? For that, we have ValueError, which can be added like so:
except ValueError:
print("Please input a valid number.")
Add the above two lines to the bottom of your exception.py file and close/save it. Run the program again and enter 90 for the first value and a for the second. The output will be:
Please input a valid number.
Exception as e
There’s another fun method of exception handling I want to mention, which is Exception as e. I’ll demonstrate this method by using it to throw an IndexError when a list index is out of range.
Say, for example, we create a list of four colors:
colors = ['red', 'blue', 'yellow', 'green']
In Python, lists are indexed starting at 0, so we have:
red = 0
blue = 1
yellow = 2
green = 3
If we add a print function but have it display the fourth index, this will cause an error.
First, let’s add the following code to a new file, colors.py: