How to catch multiple exceptions in one line (except block) in Python?

In Python, instead of writing separate except blocks for each exception, you can handle multiple exceptions together in a single except block by specifying them as a tuple.

Basic Syntax

The syntax for catching multiple exceptions in one line ?

try:
    # code that might raise exceptions
    pass
except (Exception1, Exception2, Exception3) as e:
    # handle all these exceptions the same way
    print(f"Caught an exception: {e}")

Example: Catching ValueError and TypeError

In this example, we are catching both ValueError and TypeError using a single except block ?

try:
    x = int("abc")   # Raises ValueError
    y = x + "5"      # Would raise TypeError if above line did not error
except (ValueError, TypeError) as e:
    print("Caught an exception:", e)
Caught an exception: invalid literal for int() with base 10: 'abc'

Why Handle Multiple Exceptions Together?

You can avoid repeating the same code (duplicacy) for different errors by putting multiple exceptions in a single except block. It keeps your error handling simple and organized when you want to do the same thing for different types of errors.

Example: Handling File-Related Errors

In this example, we handle both FileNotFoundError and PermissionError together as they require the same response ?

try:
    with open("file.txt") as f:
        data = f.read()
except (FileNotFoundError, PermissionError):
    print("Cannot open the file due to missing file or permissions. Creating the file now.")
    with open("file.txt", "w") as f:
        f.write("")  # create an empty file
Cannot open the file due to missing file or permissions. Creating the file now.

Accessing the Exception Object

When catching multiple exceptions, you can assign the exception instance to a variable using the as keyword. This allows you to inspect or log the error message.

Example: Printing the Exception Message

In this example, the exception object is captured and printed ?

try:
    num = int("xyz")
except (ValueError, TypeError) as error:
    print("Error occurred:", error)
    print("Exception type:", type(error).__name__)
Error occurred: invalid literal for int() with base 10: 'xyz'
Exception type: ValueError

When Not to Catch Multiple Exceptions Together

Sometimes, different exceptions need different handling. In such cases, we need to use separate except blocks instead of grouping them.

Example: Separate Exception Handling

In this example, we handle ValueError and TypeError differently ?

try:
    x = int("abc")
    y = x + "5"
except ValueError:
    print("ValueError: Invalid conversion to integer.")
except TypeError:
    print("TypeError: Cannot add string to integer.")
ValueError: Invalid conversion to integer.

Common Exception Groups

Here are some common exception combinations you might want to catch together ?

# Mathematical errors
try:
    result = 10 / 0
except (ZeroDivisionError, ValueError, OverflowError) as e:
    print(f"Math error: {e}")

# Input/Output errors
try:
    with open("data.txt") as f:
        content = f.read()
except (FileNotFoundError, PermissionError, IOError) as e:
    print(f"File operation failed: {e}")
Math error: division by zero

Conclusion

Use tuple syntax (Exception1, Exception2) to catch multiple exceptions in one except block when they require the same handling. Use separate except blocks when different exceptions need different responses.

Updated on: 2026-03-24T16:19:56+05:30

584 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements