Writing “try-except” With 2 Different Errors in Python

In this article, we’ll learn how to use the try-except to handle 2 different errors/exceptions. We’ll go over the syntax and a bunch of examples to help us understand along the way.

How to write a try and multiple except block

Whenever an error is triggered in Python, the program terminates prematurely. To avoid this, we handle the error using try-except blocks.

Similarly, when a program might potentially trigger multiple exceptions, we handle them accordingly using multiple except blocks.

The syntax to do this is pretty simple:

try:
    #some code that might trigger an error
except exception1:
    #code to handle exception1
except exception2:
    #code to handle exception2

You just mention a specific exception name next to the except keyword and that block will handle that specific exception in case it is triggered. 

If you are new to the topic of exceptions, I highly suggest reading our article

Exceptions in Python: Explained for Beginners!

Here’s an example:

try:
    my_file = open("example.txt", "r")
    my_content = my_file.read()
    my_content.close()
except FileNotFoundError:
    print("Error: No such file or directory exists!")
except IsADirectoryError:
    print("Error: That is a directory, not a file!")

This file-handling program uses the try-except blocks with multiple except statements to handle multiple exceptions.

These are common exceptions that may arise when dealing with files, I.e. the FileNotFoundError and the IsADirectoryError. If you wish to master exceptions and make your Python programming life a bit easier it is important to be familiar with these 7 Exceptions in Python.

7 Most Common In-Built Exceptions in Python!

The gif below shows how execution reaches the 1st except clause.

If you are interested in learning how to catch more than 2 exceptions using a single except block checkout our other article below.

Python: Catch Multiple Exceptions

Also it is worth mentioning that there is another closely related syntax “except Exception as e“. To learn what it means I invite you to check out the video we made on that topic below.

Adding a finally block

If you have a keen eye, you would’ve noticed a mistake in the first program in the try block. There we see there’s a chance the file may not be closed if an exception is triggered.

This is because when an exception is triggered in the try block, the interpreter does not continue the execution of the rest of the code but rather skips to the except or the finally block:

The problem with this is that our file is not closed and we are wasting memory space.

The solution to this is to simply include a finally block and move the file closing statement there:

try:
    my_file = open("example.txt", "r")
    my_content = my_file.read()
except FileNotFoundError:
    print("Error: No such file or directory exists!")
except IsADirectoryError:
    print("Error: That is a directory, not a file!")
finally:
    #checking if the first was opened first
    if 'my_file' in locals():
        my_content.close()

If this short explanation leaves you with more questions than answers, I suggest reading our complete article on the finally keyword which you can find in the link below.

Python: “try-except-finally” Usage Explained!

And with that, we end the article!

I hope this helped you understand how to use multiple except statements!

If you wish to delve deeper into this topic and pretty much handle errors like a pro, the following articles will be the next ones to tackle!

Related Articles

Python: “try-except-else-finally” Usage Explained!

7 Most Common In-Built Exceptions in Python!

Exceptions in Python: Explained for Beginners!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn