Hello everybody,
Michael here, and today I thought I’d start a new series of Python lessons. In this post, I’ll cover exception handling in Python.
For those who are unfamiliar with exception handling in programming, it’s the process of handling errors that may arise in your code (I covered exception handling in Java in the post Java Lesson 12: Try-Catch & Exception Handling).
Exception handling in Python is quite similar to Java exception handling but instead of the try-catch statement that Java uses, Python uses try-except. Let’s see some Python exception handling in action:
try:
print(4/0)
except:
print("Divide by 0 error!")
Divide by 0 error!
In this simple error-handling example, I place the code I want to error-test in the try block and I place the exception I want to display in the except block.
What happens if the code has no errors? How should you handle this? Here’s how:
try:
print(4/1)
except:
print("Divide by 0 error!")
finally:
print("Success!")
4.0
Success!
If the code in your try block doesn’t have any errors, you should include a finally block with code to execute the rest of the code. The finally block will execute regardless of the results of the try and except blocks so even if the try block caught an error and the except block gets executed, the finally block will still be executed.
Now, let’s see what happens when you don’t include a try-except block in your code:
print(4/0)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-9-4bf1a7e4a751> in <module>
----> 1 print(4/0)
ZeroDivisionError: division by zero
If you don’t have a try-except block in your code and the program has an error, the program simply crashes and throws an error. With a try-except block (or a try- except-finally block) in your code, you can catch errors that your program might raise and keep the program running regardless of how many errors it catches.
Now, what if there were several possible errors you wanted your code to catch? In Python, you can have as many except blocks as you want, but you’d need to put each possible error in it own except block. Here’s how to utilize several except statements in your code:
try:
print(3.5/0)
except ZeroDivisionError:
print("Divide by 0 error!")
except:
print("No floats allowed")
Divide by 0 error!
In this example, I have a try block along with two except blocks. The first except block catches any divide by 0 errors (referred to in Python as ZeroDivisionErrors) that are found in the try block. If there are no divide by 0 errors, the second except block will run IF there are float values in either the dividend or the divisor (I didn’t configure any input validation in my code but you get the point).
Last but not least, is it possible for you to raise an exception based on a specific condition (like if something happens, raise an exception) ? Yes, and here’s an example of how to do so:
password = str(input("Please create a password: "))
if len(password) < 8:
raise Exception("Please use 8 characters or more for your password!")
Please create a password: hola
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-14-3ae89fecd594> in <module>
2
3 if len(password) < 8:
----> 4 raise Exception("Please use 8 characters or more for your password!")
Exception: Please use 8 characters or more for your password!
In this example, the user is asked to create a password and if the password is less than 8 characters, an exception is thrown. Since the password I used for this example-hola-only has 4 characters, the exception was thrown with the custom message “Please use 8 characters or more for your password!”.
- If you want to raise an exception based off of a specific condition, use an if statement with the
raisekeyword, not a try-except block. - You don’t necessarily need a corresponding else statement if you’re raising an exception from a condition, but you should use an else statement if you want a block of code to continue running if no error is thrown.
Python also has plenty of built-in exception types that you can throw based off a certain condition. Here’s an example of one of Python’s many built-in Exception types at work:
username = "employee1"
password = "companywifi"
usernameInput = str(input("Please input your username: "))
passwordInput = str(input("Please input your password: "))
if (usernameInput != username) & (passwordInput != password):
raise PermissionError("Incorrect username and/or password!")
else:
print("Welcome")
Please input your username: GoBrowns2020
Please input your password: ILUVWORK
---------------------------------------------------------------------------
PermissionError Traceback (most recent call last)
<ipython-input-18-fd8de8965591> in <module>
6
7 if (usernameInput != username) & (passwordInput != password):
----> 8 raise PermissionError("Incorrect username and/or password!")
9 else:
10 print("Welcome")
PermissionError: Incorrect username and/or password!
In this example, I created a simple login authenticator where a employee of a company enters their username and password to access their work laptop. However, if they don’t use the preset username/password combo, then a PermissionError is thrown and the message “Incorrect username and/or password!” is displayed. However, if they use the preset username/password combo, the message “Welcome” is displayed and the user is logged on to the laptop.
- If you ever needed a simple login authenticator for any program you’re creating, this code will certainly come in handy-customize it however you like!
- As I mentioned earlier, Python has plenty of built-in exceptions that you can use-here is a link to the documentation that lists all the Python exceptions available https://docs.python.org/3/library/exceptions.html#os-exceptions (this link is for Python 3.9.2, which is the latest version as of March 2021).
Thanks for reading,
Michael
