Python Try Expect is very useful to catch an unexpected error or to create an exception to a known and/or unknown error. In this tutorial, you will be able to learn everything that is important to know about Python’s try-except and how to raise an exception.
1. Using Try Except
First and foremost, the try block lets you test a block of code for errors, and the expect block allows you to define how to handle the raised error. Simple, isn’t it?
For example, we should not be able to divide a number by 0. When trying it in Python, an error message should be raised and your code will not successfully terminate.
x = 10
y = 0
z = x/y
print(z)
This will raise an error message
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
Moreover, we can define what will happen when an error is raised when using a try clock, and you can see how to raise an exception.
x = 10
y = 0
# try to divide
try:
z = x/y
# define what is done in case of error
except:
raise Exception("Something went wrong. We are setting z = -1")
Finally, the program was able to successfully end:
>>> Exception: Something went wrong. We are setting z = -1
Including an Else statement to try-except
Ideally, you want to wrap the code that may break with the try block and anything else should go under the else statement. See below.
x = 10
y = 1
# try to divide
try:
z = x/y
# define what is done in case of error
except:
raise Exception("Something went wrong. We are setting z = -1")
else:
print(z)
prints 10.0
Using More Than One Except Block
You can define more than one except block if you know what type of error you want to catch. For instance, in the example above, we were expecting a ZeroDivisionError message, so we can put a specific action to that error and another expect to a general error.
x = 10
y = 0
# try to divide
try:
z = x / y
# define what is done in case of error
except ZeroDivisionError:
print("{} can't be divided by {}".format(x, y))
z = None
except:
print("Something went wrong. We are setting z = -1")
z = -1
else:
print(z)
prints
>>> 10 can't be divided by 0
In conclusion, you probably noticed how useful the try block can be. However, attention, avoid using it deliberated. it is important to try to catch the error based one some specific known error as don’t on this tutorial with the ZeroDivisionError.
More Resources
Here are three of my favorite Python Books in case you want to learn more about it.
- Python Cookbook, Third Edition by David Beazley and Brian K. Jones
- Learning Python, 5th Edition Fifth Edition by Mark Lutz
- Python Pocket Reference: Python In Your Pocket by Mark Lutz