Boost Your Skills with Try and Except in 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:
- ZeroDivisionError: A ZeroDivisionError print out occurs when you’ve tried to divide by zero. It’s an easy enough mistake to make if you aren’t validating your data. As you know from math classes, dividing by zero is simply impossible. While some languages might just return “0,” Python returns an error because it doesn’t want to continue with calculations that could be incorrect.
- ValueError: A ValueError print happens when a function has received a value of a different type than it was expecting. So, consider that you might have a “string” value and try to put an array into it. The program will throw an exception because the value simply cannot go where you’re trying to put it.
- KeyboardInterrupt: A KeyboardInterrupt occurs when a user hits an interrupt key during the program’s operations. This type of exception is actually very valuable, as you can make it so that the program can always interrupt itself when a user needs it to. This is part of GUI programming and interactivity.
- SyntaxError: Syntax errors happen, of course, all the time. When something isn’t typed correctly, it becomes a syntax error. But you can also throw an exception when there’s a significant syntax error.
- FileNotFoundError: You try to open a file, and it’s not found. That will lead to a FileNotFoundError. This can happen if you’re porting your code elsewhere and don’t actually have the files where they need to be.
Last Updated July 2023
Learn Python like a Professional Start from the basics and go all the way to creating your own applications and games | By Jose PortillaExplore 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:
In the above syntax:
- <do something> is the block of code that you want to complete.
- <exception> is what happens if the block of code could not complete.
Top courses in Python
Let’s look at an example: We want to open a file:
print(“We couldn’t open that document.”)
print(“We opened the document.”)
Let’s break down these lines of code:
This is the primary action we’re trying to take: We’re trying to open this file:
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:
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:
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:
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:
The above Custom Exception is empty. To create the actual error, you would add text before “pass”:
print(“User information incomplete”)
Now, to actually call this exception, you will raise it:
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.
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?
Top courses in Development
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
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!”)
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.