TNS
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
NEW! Try Stackie AI
Python

Python: How to Work with Basic Exception Handling

No matter how good a programmer you are or will be, things happen that are out of your control. That's why Python includes exception handling.
Feb 23rd, 2024 5:00pm by
Featued image for: Python: How to Work with Basic Exception Handling
Feature image by wal_172619 from Pixabay.
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:
try:
  colors = ['red', 'blue', 'yellow', 'green']
  print(colors[4])
If we run that program, it will throw the following error:
File "/home/jack/colors.py", line 4

SyntaxError: expected 'except' or 'finally' block

That’s not very helpful. Go back to the program and add a bit of exception handling:
except Exception as e:
  print(e)
  print('There is no item at index 4.')
Save and close the edited file. When you run the program now, the output will be:
There is no item at index 4.
That error is much more understandable than the previous one. And that, Python beginners, is how you can handle exceptions in your code.
Group Created with Sketch.
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.