How Do You Catch Multiple Exceptions in Python?


You can catch multiple exceptions in Python by grouping them inside a tuple in a single except block. This approach reduces repetitive code and makes error handling cleaner and more maintainable.

Modern Python applications interact with files, APIs, and databases—each capable of raising different exceptions. Handling them efficiently is critical for building reliable, production-ready software without cluttering your codebase.

Key Takeaways of Catch Multiple Exceptions in Python

  • Tuple-based exceptions → Handle multiple errors in one block
  • Cleaner code → Avoid repetitive except statements
  • Better debugging → Centralized error handling
  • Industry standard → Used in real-world Python applications

What Does Catching Multiple Exceptions in Python Mean?

Exception handling in Python allows your program to respond gracefully when errors occur instead of crashing. These errors are handled using the try and except blocks.

Catching multiple exceptions means handling more than one possible error that may arise from a single operation. For example, user input, file reading, or API data parsing can fail in different ways but still require a similar response.

Flowchart showing Python exception handling flow using try, except, else, and finally blocks with matched and unmatched exceptions.

How Do You Catch Multiple Exceptions in Python Using a Tuple?

Python allows you to catch multiple exceptions by placing them inside a tuple in a single except block.

Syntax

try:
    # risky code
except (Exception1, Exception2):
    # handle exceptions

The tuple tells Python to execute the except block if any one of the listed exceptions occurs. This approach reduces repetitive code and improves readability.

Example: Catch Multiple Exceptions in Python Using a Tuple

Below is a simple example that handles both ValueError and TypeError using a tuple:

try:
    number = int(input("Enter a number: "))
    result = 10 + number
    print(result)
except (ValueError, TypeError):
    print("Invalid input. Please enter a valid number.")

Output

  • If the user enters a string → handled as ValueError
  • If the input type is invalid → handled as TypeError

Instead of crashing, the program displays a helpful message.

When Should You Use Tuple-Based Exception Handling?

Tuple-based exception handling is best used when multiple exceptions require the same handling logic.

Common Use Cases

  • Input validationValueError, TypeError
  • File handlingFileNotFoundError, PermissionError
  • API responsesKeyError, JSONDecodeError
  • Type conversionsTypeError, ValueError

This method keeps your code concise and easier to maintain.

What Happens If an Exception Is Not in the Tuple?

If an exception occurs that is not included in the tuple, Python will not catch it.

Result

  • The program terminates immediately
  • A traceback error is displayed
  • Remaining code is not executed

To prevent this, you can:

  • Add additional exceptions to the tuple
  • Use a separate except block
  • Use a general except Exception: as a fallback (with caution)

Handling Multiple Exceptions

python
try:
    # Some code that may raise different exceptions
    result = 10 / 0
    print(int('not_a_number'))
except (ZeroDivisionError, ValueError) as e:
    print(f"An error occurred: {e}")
  

Explanation of the Code

In this code snippet, we’re handling situations where multiple errors might occur due to invalid operations. Here’s a breakdown:

  1. We use a try block to wrap the code that’s prone to raising exceptions. Our first risky operation is 10 / 0. This doesn’t fly in Python because dividing by zero is mathematically undefined. This shoots us a ZeroDivisionError.
  2. The next line tries to convert the string 'not_a_number' into an integer with int('not_a_number'). Surprise, surprise—it can’t do that and throws a ValueError.
  3. We cleverly use an except block to catch and handle these exceptions. Grouped together, ZeroDivisionError and ValueError are caught as e.
  4. When any of these errors pop up, the program doesn’t crash. Instead, it coolly prints out, “An error occurred: {e}”, telling us what went wrong.

Output

An error occurred: division by zero

Comparison of Catch Multiple Exceptions in Python

Single Exception vs Multiple Exceptions (Tuple)

Diagram comparing single exception handling versus multiple exception handling using a tuple in Python with code structure and flow differences.
FeatureSingle ExceptionTuple Exceptions
Code LengthLongerShorter
ReadabilityLowerHigher
ScalabilityLimitedHigh
Best Practice

Learn Catch Multiple Exceptions in One Line in Python, Now!

Real-Life Applications of Catching Multiple Exceptions in Python


  1. E-commerce Transactions (Amazon)
    Amazon handles millions of transactions every day. To ensure smooth payment processes, they use multiple exceptions catching to manage potential errors like connection timeouts or invalid payment details.

    try:  
    process_payment()
    except (ConnectionTimeoutError, InvalidPaymentDetailsError) as e:
    log_error(e)
    send_alert_to_user()
    Output:
    By catching exceptions efficiently, Amazon reduces unsuccessful payment issues, enhancing customer satisfaction through quick error resolution.

  2. Data Processing (Spotify)
    Spotify analyzes streaming data in real-time. With diverse data sources, issues like missing or corrupt data are common. Catching various exceptions ensures seamless data processing without abrupt interruptions.

    try:  
    process_streaming_data()
    except (MissingDataError, CorruptDataError) as e:
    handle_data_error(e)
    continue_processing()
    Output:
    This allows Spotify to maintain music streaming without service dips, ensuring users enjoy a consistent experience.

  3. User Authentication (Facebook)
    Facebook uses multiple exception catching for user authentication processes, handling issues like invalid passwords or expired tokens gracefully.
    try:  
    authenticate_user()
    except (InvalidPasswordError, ExpiredTokenError) as e:
    prompt_user_for_confirmation(e)
    Output:
    The use of multiple exceptions helps Facebook maintain security standards while reducing user login frustrations.

Catch Multiple Exceptions in Python: Interview Questions

  1. What is the difference between catching multiple exceptions using a tuple and using multiple except blocks?
    Catching multiple exceptions using a tuple allows you to handle several exceptions with a single piece of code. In contrast, using multiple except blocks lets you handle each exception with specific code. Here’s an example using a tuple:
    try:
    # risky code
    except (ValueError, KeyError) as e:
    print(f"Handled error: {e}")
  2. Can I catch all exceptions in Python? If so, how?
    Yes, you can catch all exceptions by using the broadest exception class, which is Exception or simply by catching BaseException. However, use this sparingly as it may hide bugs.
    try:
    # risky code
    except Exception as e:
    print(f"Generic error caught: {e}")
  3. How can I catch and handle exceptions specific to a particular module?
    Import the module first, then catch exceptions raised within that module. For instance, for HTTP requests:
    import requests

    try:
    response = requests.get('http://example.com')
    except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
  4. Is it possible to re-raise a caught exception in Python? Why would you do this?
    Yes, you can re-raise an exception using raise without specifying the error type. This might be useful to log an error before terminating or passing it to another handler.
    try:
    # risky code
    except ValueError as e:
    log_error(e)
    raise
  5. How does the ‘else’ block work in exception handling?
    The ‘else’ block runs if no exceptions are raised in the try block, providing further actions that should only be executed upon successful execution of try.
    try:
    result = 10 / 2
    except ZeroDivisionError:
    print("Division by zero!")
    else:
    print("Success, result is", result)
  6. What is the purpose of the ‘finally’ block in exception handling?
    The ‘finally’ block is used to execute code that must run regardless of whether an exception occurred. It’s often used for cleanup actions like closing files or releasing resources.
    try:
    file = open('test.txt', 'r')
    except FileNotFoundError:
    print("File not found!")
    finally:
    file.close()
  7. How can I create custom exceptions in Python?
    Create a custom exception by subclassing Exception and adding any additional functionality needed.
    class CustomError(Exception):
    pass

    try:
    raise CustomError("This is a custom exception")
    except CustomError as e:
    print(e)
  8. Can I catch both Python built-in and custom exceptions in a single block?
    Yes, use a tuple in the except clause to catch multiple built-in and custom exceptions.
    try:
    potentially_failing_code()
    except (ValueError, CustomError) as e:
    print(f"An error occurred: {e}")
  9. How do I ignore exceptions without stopping program execution?
    You can ignore exceptions by using a bare except block or logging errors without taking any action. This isn’t recommended unless you’re sure of the safety.
    try:
    # risky code
    except:
    pass

Imagine a world where coding becomes a breeze! With our AI-powered python online compiler, you can write, run, and test your code instantly. No more waiting around. Our tool streamlines your coding process, making programming faster and more efficient. Dive in and see for yourself!

Conclusion

“Catch Multiple Exceptions in Python” empowers you to handle errors elegantly, offering a smoother, more robust coding experience. Mastering it boosts your coding confidence. Ready to learn more and level up your skills? Check out Newtum for resources on Java, C, C++, and more programming languages.

Edited and Compiled by

This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.

About The Author