Python Exceptions: A Guide
Exceptions can be raised by the Python interpreter and manually. Built-in exceptions help catch common errors in a program.
In this guide, we’re going to discuss what an exception is and how they are used. We’ll walk through an example of how to raise an exception so you can work with them in your code.
What is an Exception?
An exception, also called a logical error, is an error that occurs during program runtime.
Find Your Bootcamp Match
Career Karma matches you with top tech bootcamps
Access exclusive scholarships and prep courses
By continuing you agree to our Terms of Service and Privacy Policy , and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
There are two types of errors in Python:
syntax errors
and runtime errors. Syntax errors are raised before a program runs. If your program encounters a syntax error, your program will not be able to run. This is because Python cannot interpret code that contains syntax errors.
Runtime errors, also called exceptions, are encountered while Python runs a program. An exception may be raised on line 30 of a program. If an exception is raised on line 30, 30 lines of code will run, then the program will stop.
Here is an example of an exception:
Traceback (most recent call last): File "main.py", line 6, in <module> s_names.append(n) AttributeError: 'str' object has no attribute 'append'
This exception tells us Python cannot run the rest of our code. If you encounter an exception, you should carefully read the message. The error message will tell you most, if not all, of what you need to know to solve an error.
Let’s break down the last sentence in our error message:
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
AttributeError: ‘str’ object has no attribute ‘append’
In this case, we know our error is an AttributeError. This means we’re trying to reference an attribute that does not exist. Our error message tells us we are trying to use append() on a string object, which is not allowed.
Because string objects do not support the
append()
method, a good next step is to look for the equivalent of
append()
for strings. This is concatenation. Now we have a potential solution to our programming issue that we can apply.
Where May I Encounter an Exception?
To help programmers catch errors in their code, Python has a range of built-in exceptions. These exceptions can help you identify the cause of an issue in your code so you can fix them. Below are a few of the most common exceptions you’re likely to encounter:
- TypeError: Occurs when you apply a function to an object whose type does not support that function. (e.g. TypeError: can only join an iterable )
- SyntaxError: Raised before a program executes to tell you that there is an issue in your syntax (e.g. SyntaxError: invalid syntax)
- KeyError: Occurs if you reference a key in a dictionary that does not exist. (e.g. KeyError: “usb_ports ”)
- ImportError: Occurs if you try to import a package that does not exist, or a function from a package that does not exist.
We’ve only listed a few of the many exceptions that you may encounter in the Python language.
How to Raise an Exception
You can define your own custom exceptions in your code. This can be helpful if the built-in exceptions provided by Python do not suit the needs for your program.
We’re going to write a program that validates a password for a game. To start, let’s ask the user to insert a password:
password = input("Enter a password: ")
For the user’s password to be valid, it must be more than 12 characters long. If the user’s password is 12 characters or fewer, we want to raise an exception.
To do this, we’re going to use an
if statement
. The following if statement will check if the password a user has chosen is fewer than 12 characters:
if len(password) > 12: print("Your password is valid.") else: raise Exception("Your password is not the correct length.")
We use the
len() method
to calculate the length of a user’s password. If a user inserts an invalid password, our program will raise an exception with a message stating “Your password is not the correct length.”
Let’s try out our code to see if it works:
Enter a password: Bacon120 Traceback (most recent call last): File "main.py", line 6, in <module> raise Exception("Your password is not the correct length.") Exception: Your password is not the correct length.
The password we entered was under 12 characters. Our code stops because we entered an invalid password. Let’s try to run our program with a valid password:
Enter a password: Bacon120Bacon120 Your password is valid.
Our program executes successfully.
How to Handle an Exception
By default, exceptions will stop the execution of a program. While this is useful because it forces you to find the solution to an error, there are some cases where you may not want your program to stop executing if an exception is raised.
For instance, if you are checking if data points in a list are valid, you may not want an exception to be raised every time an invalid data point is discovered.
To handle an exception, you can use a “try…except” block. Let’s write a program that finds an item in a dictionary. This dictionary contains a list of names of students in a class and their corresponding grades on their most recent test.
To start, let’s define a dictionary with student and grade information:
data = { "Lucy": 73, "Carlton": 59, "Adam": 73 }
Next, let’s ask a user to insert a name whose grade they want to retrieve. We’re going to do this within a “try” block so that we can handle an exception later in our code:
try: student = input("Enter the name of the student whose grade you want to retrieve: ") print(data[student])
This code will print out the grade of the student whose name matches the one that a user has inserted into the program. However, if a user inserts a name that is invalid, a KeyError will be encountered.
We’re going to handle this by adding an except block to our code:
try: student = input("Enter the name of the student whose grade you want to retrieve: ") print(data[student]) except: print("This student is not present in the list of grades.")
If a student cannot be found, the except clause is executed. Let’s run our program:
Enter the name of the student whose grade you want to retrieve: Lucy 73
When we enter a valid student name, our program works. Let’s try our program if we insert an invalid student name:
Enter the name of the student whose grade you want to retrieve: Kaitlin This student is not present in the list of grades.
An exception is raised but our program does not stop. Instead, the contents of the “except” block are executed.
To learn more about the try…except block, read our guide on Python try…except .
Conclusion
Exceptions inform you there is a logical error in your code. When an exception is raised, you should see the type of the exception, where the exception was raised, as well as an error message. You can use this information to find the cause of the exception.
You can raise your own exceptions using the raise statement. You can handle exceptions using the try…except block of code.
Now you have the tools you need to solve a Python exception like a pro!