Python try except blocks are a built-in function used for debugging. Try except allows you to run a block of code and return a specific error in the event of a bug.
When you’re programming, you may want to test a specific block of code to ensure it functions correctly before allowing the rest of the program to run. For example, you may have written a large amount of code and want to make sure it works before letting the rest of the program run.
In Python, there is a built-in function that allows you to test code quickly and handle any errors and exceptions that may come up: the try/except blocks.
In this tutorial, we are going to break down the basics of exception handling in Python, and when you may want to use the try/except blocks to test your code.
Python Errors and Exceptions Refresher
In Python, there are two kinds of errors you may encounter: syntax errors and exceptions.
Syntax errors are a type of error that returns when you miswrite code. For example, if you write a
while True loop without a colon at the end, the program will give you an error. Syntax errors return the file name, line number, and an indicator of where an error may be present.
Exceptions are a type of error where code may have the right syntax but still contains a problem. There are many different types of exception, but some of the most common you will encounter include: ArithmeticError, ImportError, ZeroDivisionError, NameError, and TypeError.
Let’s show some examples of an exception to illustrate how they may appear in our code. Here is an example of a ZeroDivisionError:
1 * (1/0)
Our program understands that while our code may be technically correct — we have used the right operators and syntax — we cannot divide a number by zero. So, our code returns the following:
Traceback (most recent call last): File "main.py", line 1, in <module> 1 * (1/0) ZeroDivisionError: division by zero
Here’s an example of a TypeError:
Traceback (most recent call last): File "main.py", line 1, in <module> print(ourVariable) NameError: name 'ourVariable' is not defined
In this case, we have used the correct syntax—we are printing a variable —but we have not declared our variable. Thus, our program returns a NameError.
These errors, while useful, are also very technical. And if we are testing code, we may want to create our mistakes based on our needs. We can use the try/except block as a method of parsing our errors.
Python Try Except
When you’re programming, you’ll likely encounter errors, whether they are exceptions or syntax errors. Thus, it is always wise to test code before making it part of a more substantial program. This is where the try/except blocks come in.
The try block allows you to test a block of code for errors, and the except block enables you to handle the error. Here’s an example of the syntax for try/except blocks:-
try: print(ourVariable) except: print('Error returned')
In the above example, we have not declared the variable
ourVariable. If we did not have try/except blocks in our code, the program would return an error. But because we have try/except blocks, our code knows what to do when an error is encountered.
Here is the result of our code:
Try/except blocks can be useful if you need to test out a block of code and want a specific error to be returned.
Multiple Except Statements
In addition, if you want to test for multiple exceptions, you can repeat
except statements for different types of errors. Here is an example of try/except blocks that look for a NameError:
try: print(ourVariable) except NameError: print('ourVariable is not defined') except: print('Error returned')
In this case, our code returns
ourVariable is not defined because our code returns a NameError.
Similarly, if your code works correctly, you can add the
else keyword. By using an else clause, you can define code that will be run in the case that no exceptions are raised. Here’s an example:
try: print('Test') except: print('There is a problem.') else: print('There are no problems.')
Our code returns the following:
There are no problems.
In the above example, our Python program encounters no exceptions, so the code within the
else statement executes, and the
else prints out the message stating there are no problems with our code.
But what if we want a message to print both if an error is returned and if no error is found? That’s where the
finally block comes in. If you define a finally clause, its contents will be executed irrespective of whether the try/except block raises an error. Here’s an example:
try: print(ourVariable) except: print('ourVariable is not defined') finally: print('Code has been run.')
Our program returns the following:
ourVariable is not defined Code has been run.
The code within the
except block executes because there is an exception found in our code (ourVariable is not defined). The code within the
finally clause executes as well, because our code has finished running.
That’s how you use the try/except blocks in Python! In this tutorial, we have broken down how to use try/except blocks, and we have discussed how to use
except to customize your exception handling. These blocks can be useful when you’re testing existing code or writing new code. It ensures that your program runs correctly and contains no errors.