person holding post it with the word python

Python is an easy language to learn, but it has some intermediate to advanced concepts too. One of these is the Python TRY statement. Python’s TRY statement is part of a larger TRY/EXCEPT statement—designed for exception catching. It’s a fairly intermediate Python concept and an extremely useful one. So if you want to know how to catch exceptions with Python, you need to know about Python TRY. 

Today, we’re going to look at how to use Python TRY, when to use it, and some alternatives.

What is an exception?

An exception is an issue that can potentially cause Python programs to crash. When the program encounters exceptions, it sends an error to the interpreter. Importantly, because Python is an interpreted language rather than a compiled language, these errors may not get caught until after writing the code.

Examples of Python exceptions include:

The Complete Python Bootcamp From Zero to Hero in Python

Last Updated July 2023

  • 156 lectures
  • All Levels
4.6 (516,828)

Learn Python like a Professional Start from the basics and go all the way to creating your own applications and games | By Jose Portilla, Pierian Training

Explore Course

These exceptions are critical exceptions—the program cannot continue after this type of error. If the program continued after this error, too much would go wrong. If you look at some common integer and string methods, you can see how certain functions could cause problems if run incorrectly.

An easy example is reading from a file. If the file is not found, then the rest of the code could continuously reference a file that doesn’t exist. This would simply spawn large volumes of errors.

Because you may not encounter this upon compilation, since Python is interpreted, you have to instead repeatedly check to see whether an exception occurred. This is where Python TRY comes in.

Errors vs. exceptions

What’s the difference between an error and an exception? While there are other definitions, an error generally occurs when you go to write your code. An exception is something that occurs when the code is run.

Python being an interpreted language means that the lines between errors and exceptions can blur. For instance, in Java, an error would occur when you go to compile your code—an exception would occur when a user went to run the code. Learning more about basic Python can help you understand the differences between compiled and interpreted languages. 

In Python, the error occurs when the parser attempts to run the code. But an error will occur consistently, whereas an exception is an error that only sometimes happens during the runtime of the program. And when the exception occurs, it will generally make it impossible for the program to continue.

Because we don’t want our programs to crash, we program in additional blocks of code that will happen if an exception occurs. 

What is Python TRY?

The Python TRY command tries a given clause. If it’s not successful, it prints an error message or otherwise handles the error. Both the initial clause and the error clause will be user-defined. 

Here’s the syntax of Python TRY:

try:
<do something>
except Exception:
<exception>

In the above syntax:

This is very similar to the same concepts in JavaScript; only the syntax is different. Additionally, there are the “else” and “finally” values—but we’ll take it one step at a time.

Top courses in Python

Python for Beginners
Navin Reddy
4.6 (9,459)
Python for Beginners (2023)
AlgoSTEM Inc.
4.4 (3,109)
Python 3: Deep Dive (Part 1 – Functional)
Dr. Fred Baptiste
4.8 (11,674)
Python for Data Analysis & Visualization
Malvik Vaghadia, Pathfinder Analytics
4.6 (1,625)
100 Days of Code: The Complete Python Pro Bootcamp
Dr. Angela Yu, Developer and Lead Instructor
4.7 (321,582)
Bestseller
Learn Python & Ethical Hacking From Scratch
Zaid Sabih, z Security
4.7 (19,788)

More Python Courses

Let’s look at an example: We want to open a file:

try:
open(“file.doc”)
except:
print(“We couldn’t open that document.”)
else:
print(“We opened the document.”)
finally:
print(“Anything else?”)

Let’s break down these lines of code:

try:
open(“file.doc”)

This is the primary action we’re trying to take: We’re trying to open this file:

except:
print(“We couldn’t open that document.”)

This EXCEPT action only occurs if we can’t open the document. Importantly, it will occur at any time we can’t open the document. If we want to be more specific, we could do something like this:

except FileNotFoundError:
print(“This file was not found.”)

This would only print that particular text if the file wasn’t found. In general, it’s good to be as specific as possible—but you should also have a generally applicable exception clause:

else:
print(“We opened the document”)

This ELSE block only runs IF an exception didn’t occur. That’s what makes it an ELSE print rather than a FINALLY print. The clause is executed only if the file was successfully opened:

finally:
print(“Anything else?”)

The FINALLY keyword will always print, whether there was an exception or not. So, the FINALLY keyword refers to something that will always happen, as opposed to an ELSE print, which only occurs under certain conditions.

Critically, your final block should never assume that specific action was successful or unsuccessful because the FINALLY clause gets called regardless.

Creating your own exceptions

We looked at some of the most common built-in Python exceptions. But also note that you can create Python exceptions too. For instance, you might have objects or classes that can only take certain values or that have structures that can only operate a given way. By using Python to create custom exceptions, you can enforce these behaviors and ensure the validity of your data.

You can create a custom exception by adding another entity to the class Exception:

class CustomException(Exception)
pass

The above Custom Exception is empty. To create the actual error, you would add text before “pass”:

class CustomException(Exception)
print(“User information incomplete”)
pass

Now, to actually call this exception, you will raise it:

raise(CustomException)

Using custom exceptions is a great practice. But you still need to be conscious of the exceptions that could be raised. A custom exception is an advanced programming project—and it requires that you deeply understand the logic behind programming and issues that could arise.

Coded language on a screen with person looking at it.

When should you use TRY/EXCEPT?

So, you know that TRY/EXCEPT is designed to catch exceptions. But you also probably know that TRY/EXCEPT isn’t used every single time a clause executes. When should you use TRY/EXCEPT?

You should always use TRY/EXCEPT if you aren’t sure of the validity of the code you’re about to run. Normally, you will validate all the data that you’re given. But there are times when that can’t occur. A common enough example is user input.

If a user is inputting numbers on their side, for instance, you need to know whether it might be a zero; otherwise, you could divide by zero and run into a runtime error. Runtime errors are always bad because they can lead to the system being unusable or crashing.

Note that TRY/EXCEPT and exception handling are generally more common in the flow of Python than in other languages. In many other languages, the programmer will not have so much discrete control over exception handling.

Consider looking at some Python programming examples to see where TRY/EXCEPT is used. Are there areas that you think TRY/EXCEPT should be used but isn’t?

Why doesn’t Python automatically catch exceptions?

Python does automatically catch exceptions—by stopping the program. An exception is something that just cannot happen, such as a file not being able to open or not being able to divide by zero. Since Python cannot continue the program, the program just stops.

This is what makes exception handling important. It is essentially the programmer telling Python what it wants to do in the event that it cannot complete the previous code block. Otherwise, Python wouldn’t know what to do given that the code block that it has been given appears (to it) to be impossible to run.

Other programming languages may try to “recover” from minor exceptions—for instance, a division by zero error might show a warning but still continue to execute the rest of the code. While this does preserve the rest of the code, it can lead to highly erratic functionality, as all subsequent code will be predicated on the idea that the value (division by zero) has been successfully calculated.

Using “IF” vs TRY/EXCEPT

In many languages, you would use “IF” to catch a lot of exceptions. Python isn’t an exception to that. The practice of using “IF” to identify impossible situations is a highly well-embedded one and many programmers do it by default. The difference is that IF is generally used to track a condition that can commonly happen but doesn’t apply to the code block that you want to run. TRY/EXCEPT is really for conditions that should not happen (much like ASSERT), designed to help the system safely recover after one of these issues occurs.

Consider the “division by zero” error. With Python TRY, you would do as follows:

a = 0
b = 1
try:
print(b/a)
except ZeroDivisionError:
print(“Trying to divide by zer

Alternatively, though, you could test for this case before you even start running the code block:

a = 0
b = 1
if a == 0:
print(“Trying to divide by zero!”)
else:
print(b/a)

As you can see, we still caught the error, but we didn’t have to use TRY/EXCEPT. Instead, we just used a regular IF/ELSE statement to catch the exception that would have led to the program crashing.

This isn’t necessarily a bad thing to do. In fact, for most programmers, it’s a good habit to test out all your potential failure points before you start. But for exceptions specifically, it’s usually better hygiene to use TRY/EXCEPT.

Part of this is because the “except” case can catch all exceptions. When you use “if,” you have to go through everything that could potentially go wrong—something that is daunting at best. 

More about Python error/exception catching

Python is often lauded as an easy language to learn—and it is. But all programming languages are as much about logic as they are about programming. To really dig deeper into Python, you have to think about what will and won’t happen—about the issues that could arise when you get a little deeper into programming.

As you code, you’ll probably see many warnings pop up in your programming. You might not see exceptions, but you could see errors. It’s a best practice to dig deeper into any warnings and errors you see to learn more about the programming language.

To get more practice at Python, consider taking some Python classes or focusing on Python projects. Until then, you can learn more about the TRY/EXCEPT function by looking up other types of exceptions and how they work. You can also read up on some common Python interview questions to better understand what’s most important about the language.

Page Last Updated: March 2022