Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Catching Multiple Exceptions in Python

1 min read .
Catching Multiple Exceptions in Python

Python lets one except clause handle several exception types when they should receive the same response. This keeps error handling concise without hiding unrelated failures.

Catch Several Exception Types

Place the exception classes in a tuple:

try:
    value = int(user_input)
    result = 100 / value
except (ValueError, ZeroDivisionError) as exc:
    print(f"Invalid input: {exc}")

ValueError handles non-numeric input, while ZeroDivisionError handles zero.

File Example

try:
    with open("missing.txt", "r", encoding="utf-8") as file:
        content = file.read()
except (FileNotFoundError, PermissionError) as exc:
    print(f"Could not read the file: {exc}")

Catching OSError can also make sense when all operating-system-level failures should be handled the same way:

try:
    with open("data.txt", encoding="utf-8") as file:
        content = file.read()
except OSError as exc:
    print(f"File operation failed: {exc}")

FileNotFoundError and PermissionError are subclasses of OSError.

Use Separate Blocks for Different Recovery Logic

If each error requires a different response, separate the handlers:

try:
    value = int(user_input)
    result = 100 / value
except ValueError:
    print("Enter a valid integer.")
except ZeroDivisionError:
    print("The value must not be zero.")

Avoid Catching Exception Too Broadly

This is legal:

try:
    run_task()
except Exception as exc:
    print(exc)

But broad catches can hide bugs you did not intend to recover from. Prefer the narrowest exception types that represent expected failure modes.

else and finally

else runs only when the try block succeeds:

try:
    value = int("42")
except ValueError:
    print("Invalid number")
else:
    print(value)

finally runs whether an exception occurred or not and is useful for cleanup that is not already handled by a context manager.

Conclusion

Group exception types in one except tuple when they genuinely share the same recovery behavior. Split handlers when the response differs, and avoid overly broad catches so unexpected programming errors remain visible.

Related Posts

chevron-up