Catching multiple exceptions

Catching Multiple Specific Exceptions in Separate Blocks

You can catch multiple specific exceptions by using multiple except blocks. Each except block can handle a different type of exception.

try:
    # Code that may raise multiple exceptions
    x = int(input("Enter a number: "))
    y = 10 / x
    print("Result:", y)
except ValueError:
    print("Invalid input. Please enter a valid number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

Catching Multiple Specific Exceptions in One Block

Python allows you to catch multiple exceptions in a single except block by specifying a tuple of exception types.

try:
    # Code that may raise multiple exceptions
    x = int(input("Enter a number: "))
    y = 10 / x
    print("Result:", y)
except (ValueError, ZeroDivisionError) as e:
    print(f"An error occurred: {e}")

In this example, if either a ValueError or ZeroDivisionError is raised, the same except block will handle it.

Example: Catching and Handling Multiple Exceptions

Here’s a more detailed example that includes different types of exceptions and shows how to handle them.

def process_input(value):
    try:
        # Try converting the input to an integer
        num = int(value)
        # Try performing a division
        result = 10 / num
        print(f"Result of division: {result}")
    except (ValueError, ZeroDivisionError) as e:
        print(f"An error occurred: {e}")

# Test with different inputs
inputs = ["abc", "0", "5"]
for i in inputs:
    print(f"Processing input: {i}")
    process_input(i)

Output:

Processing input: abc
An error occurred: invalid literal for int() with base 10: 'abc'
Processing input: 0
An error occurred: division by zero
Processing input: 5
Result of division: 2.0

Combining Specific and General Exception Handling

You can combine specific exception handling with a more general except block to catch any other exceptions that you didn’t anticipate.

try:
    # Code that may raise multiple exceptions
    x = int(input("Enter a number: "))
    y = 10 / x
    print("Result:", y)
except (ValueError, ZeroDivisionError) as e:
    print(f"An error occurred: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Best Practices for Catching Multiple Exceptions

Catch Specific Exceptions First:

Always catch specific exceptions before more general ones. This ensures that specific errors are handled appropriately.

try:
    # Code that may raise exceptions
except SpecificException:
    # Handle specific exception
except Exception:
    # Handle any other exception
Use Descriptive Error Messages:

Provide informative error messages to make debugging easier.

try:
    # Code that may raise exceptions
except (ValueError, ZeroDivisionError) as e:
    print(f"An error occurred: {e}")
Avoid Catching Too Many Exceptions:

Catching all exceptions using a generic except block can hide bugs and make debugging difficult.

try:
    # Code that may raise exceptions
except Exception as e:
    print(f"An error occurred: {e}")  # Be cautious with this approach