In Development Last updated:
Share on:
Cloudways offers managed cloud hosting for any size business to host a website or complex web applications.

Catching exceptions in Python helps ensure that your programs crash less frequently. This makes your code more reliable and provides a better user experience. In this article, I will discuss how to catch multiple exceptions in the same try/except block in Python.

What are Exceptions in Python?

In Python, Exceptions are a communication mechanism between different program parts. This communication mechanism allows one part of the system to communicate that it has encountered a critical error that it does not know how to handle.

So, it raises an exception. Another part of the program that knows how to handle the error will catch the exception and handle the error properly.

When not handled, exceptions will crash the program. Handling exceptions, therefore, prevents your program from crashing and makes it more reliable.

For this article, I will assume you are already familiar with the basics of raising and handling exceptions, which is covered in this Introduction to Python Try/Except article.

Importance of handling multiple exceptions in Python

  • It reduces code duplication as multiple exceptions are handled by the same block. This makes the code easier to read, edit and delete.
  • It also helps you write more efficient code as the error type only has to be checked once instead of several times.

Handling Multiple Exceptions

Catching multiple exceptions refers to the situation where multiple exceptions are caught using the same except block. In Python, you can catch different exceptions in individual except blocks.

Alternatively, when you want to handle the exceptions in a similar way, you can handle them using one block. To do so, you will need to catch multiple exceptions. In this section, I will explain how to do that with an example.

#1. Catching Different Exceptions in Different Blocks

Suppose we had a program designed to take in two different values and divide them. In this program, we anticipate different types of exceptions will be raised when the user enters invalid values. In particular, we want to handle the ValueError and the ZeroDivisionError.

The ValueError will be raised when the user inputs a value that cannot be converted to an integer. The ZeroDivisionError will be raised when the second number is a zero. In both these cases, we want to display an error message that says, “You have entered an invalid value”.

To do the above, we can write the following code:

try:
    dividend = int(input('Enter first num: '))
    divisor = int(input('Enter second num: '))
    quotient = dividend / divisor
    print(quotient)
except ValueError as e:
    print("You entered an invalid value")
except ZeroDivisionError as e:
    print("You entered an invalid value")
except Exception as e:
    print("Something went wrong")

If we run the above code and text that cannot be converted to an integer, this will be the result:

And if we entered the second number as a 0, this would be the result:

The code works as expected, but notice that we are handling the ValueError and ZeroDivisionError similarly. So, there is a lot of code duplication between the two Except blocks. This is not ideal, as we violate the DRY principle in programming. The DRY Principle says Don’t Repeat Yourself.

So, instead of writing the code separately, we can combine the two blocks into one block that catches multiple exceptions. If we do so, we avoid the repetition.

#2. Catching Multiple Exceptions in one Except Block

To catch multiple exceptions, we provide a tuple that specifies all the errors we want to catch. Here’s an example where we catch both the ValueError and ZeroDivisionError in one except block:

try:
    dividend = int(input('Enter first num: '))
    divisor = int(input('Enter second num: '))
    quotient = dividend / divisor
    print(quotient)
except (ValueError, ZeroDivisionError) as e:
    print("You entered an invalid value")
except Exception as e:
    print("Something went wrong")

This is a much better implementation than the code before. Essentially, this is what handling multiple exceptions is about. The code above works in the same way as before. If you test using the previous examples, it should work as before:

#3. Identifying which exception has been caught

The code above executes the first except block when either a ValueError or a ZeroDivisionError has been caught. In some cases, you may have code you want to execute for both errors and some other code you want to execute for one but not the other error.

In this case, you must first identify what error has been caught and execute the appropriate code.

To identify which exception has been caught, you can use an if/else block inside the except block. For example:

try:
    dividend = int(input('Enter first num: '))
    divisor = int(input('Enter second num: '))
    quotient = dividend / divisor
    print(quotient)
except (ValueError, ZeroDivisionError) as e:
    print("You entered an invalid value")

    if isinstance(e, ValueError):
        print('Value Error')
    else:
        print('Zero Division Error')
except Exception as e:
    print("Something went wrong")

In this block, in addition to printing the generic error message for both the ValueError and ZeroDivisionError, we are also checking exactly what type of error we caught and printing an additional message. If we test the code again, we should see some additional messages specific to the exception caught.

When Would You Want to Handle Multiple Exceptions?

In the general case, handling multiple exceptions is ideal when you want to execute the same code for similar exceptions that might be raised. This includes the following:

  • Network Requests that failed for different reasons. Regardless, you may want to notify the user that the server could not be reached.
  • Failed database connections, which produce multiple errors. Although these errors might be different, your handling might be the same.
  • File I/O also produces errors that can be handled similarly, such as permission and disk full errors.

Conclusion

This article discussed combining multiple except blocks into one by catching multiple exceptions simultaneously. This helps your code become more readable and maintainable. Next, you may want to read this article on Python Beginner Projects you should try.

Share on:
  • Anesu Kafesu
    Author
    I am a Software Engineer specialising in Web Development, Mobile Application Development and Artificial Intelligence. I occasionally write on the same topics.
  • Narendra Mohan Mittal
    Editor

    Narendra Mohan Mittal is a versatile and experienced digital branding strategist and content editor with over 12 years of experience. He is a Gold Medalist in M-Tech and B-Tech in Computer Science & Engineering.


    Currently,…

Thanks to our Sponsors

More great readings on Development

Power Your Business

Some of the tools and services to help your business grow.
  • The text-to-speech tool that uses AI to generate realistic human-like voices.

    Try Murf AI
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.

    Try Brightdata
  • Monday.com is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.

    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.

    Try Intruder