In this tutorial, we’ll cover an important topic in Python programming: catching multiple exceptions in Python. With examples, I will show you, multiple exception handling in Python.
What is Exception Handling in Python?
In Python, an exception is an event that disrupts the normal execution of a program. This could be due to incorrect input, a server not responding, a file not being found, and so on. When these exceptions occur, Python halts the program and generates an error message.
We use try-except blocks to handle these exceptions and prevent our program from stopping abruptly. We’ll write the code that could potentially raise an exception in the try
block and the code that handles the exception in the except
block in Python.
Catch Multiple Exceptions in Python
In Python, we can catch multiple exceptions in a single except
block. This is useful when you have a piece of code that might raise more than one type of exception and want to handle all of them similarly.
Here’s the basic syntax for catching multiple exceptions:
try:
# code that may raise an exception
except (ExceptionType1, ExceptionType2, ExceptionType3, ...):
# code to handle the exception
Example: Handling multiple exceptions in Python
Let’s say you’re writing a Python program that reads a file and then performs a division operation with the data from the file. This code might raise several exceptions. The open()
function might raise a FileNotFoundError
if the file doesn’t exist, and the division operation might raise a ZeroDivisionError
if you try to divide by zero.
Here’s how you could catch both exceptions in Python with a single except
block:
try:
file = open("myfile.txt", "r")
number = int(file.read())
result = 100 / number
except (FileNotFoundError, ZeroDivisionError):
print("An error occurred")
In this code, if either a FileNotFoundError
or a ZeroDivisionError
is raised, the program will print “An error occurred” and continue executing the rest of the program.
However, if you want to execute different code for each exception, you would use separate except
blocks:
try:
file = open("myfile.txt", "r")
number = int(file.read())
result = 100 / number
except FileNotFoundError:
print("The file was not found")
except ZeroDivisionError:
print("Cannot divide by zero")
n this example, if a FileNotFoundError
is raised, the program will print “The file was not found”. If a ZeroDivisionError
is raised, it will print “Cannot divide by zero”.
Another Example:
Let’s consider an example where we have a Python dictionary of user data, and we’re trying to perform some operations that could raise exceptions. The operations include accessing a key that might not exist (raising a KeyError
), and converting a string to an integer (which could raise a ValueError
if the string does not represent a valid integer).
user_data = {
"name": "John",
"age": "25",
"balance": "two thousand" # This should have been a numeric string.
}
try:
# Accessing a non-existing key will raise a KeyError.
email = user_data["email"]
# Converting a non-numeric string to an integer will raise a ValueError.
balance = int(user_data["balance"])
except (KeyError, ValueError) as e:
print("An error occurred: ", str(e))
In this code, if the key “email” does not exist in the dictionary, a KeyError
will be raised. Similarly, when trying to convert the string “two thousand” to an integer, a ValueError
will be raised. Both of these exceptions are caught by the except
block, and an error message is printed.
Check out the below screenshot for the output.
Read: How to handle KeyError with Try-Except in a Python dictionary
Using as to access the Exception Object in Python
You can use the as
keyword in your except
block to access the exception object in Python. This allows you to print the error message associated with the exception, or access its other properties.
Here’s an example:
try:
file = open("myfile.txt", "r")
number = int(file.read())
result = 100 / number
except (FileNotFoundError, ZeroDivisionError) as e:
print("An error occurred: ", str(e))
In this code, if an exception is raised, the program will print “An error occurred: ” followed by the error message associated with the exception.
Conclusion
In this tutorial, we’ve discussed how to handle multiple exceptions in Python using the try-except
blocks. This is a powerful tool that allows you to create robust programs that can handle unexpected errors in Python.
You may also like:
- How to remove the last character from a string in Python
- Python Append List to another List without Brackets
- How to find perfect number in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.