Python Catch Multiple Exceptions

Learn how to catch multiple exceptions in Python using one except block with a tuple, separate except blocks, as e, else, finally, and best practices for handling multiple errors.

Published

Updated

Read time 5 min read

Reviewed byDeepak Prasad

Python Catch Multiple Exceptions

This page shows how to catch more than one exception type in Python: one except with a tuple of types, several except clauses for different recovery paths, binding the instance with as, plus else and finally. It assumes you already know a single try / except; for the full error-handling model, see Python try except. For numeric types involved in TypeError examples, see Python numbers.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.

Only one exception runs from a given try block at a time—the first line that raises wins, and the rest of the try body is skipped. Examples below use separate try blocks or loops so behavior is predictable.


Catch multiple exceptions in one except block

Group exception classes in a tuple after except. If the raised exception is an instance of any listed type, that handler runs.

python
try:
    value = int("not-a-number")
except (ValueError, TypeError) as e:
    print(type(e).__name__, e)
Output

That prints ValueError with a message about invalid literal for int().

To share one message or logging path for several related errors (for example file-related OSError subclasses), a tuple keeps the handler short:

python
try:
    open("/nonexistent/path/readme.txt")
except (FileNotFoundError, PermissionError) as e:
    print("cannot open:", e)
Output

Catch multiple exceptions with separate except blocks

List handlers most specific first, then broader types. Python checks except clauses in order and runs the first match.

python
user_input = "0"
try:
    number = int(user_input)
    result = 10 / number
except ValueError:
    print("Please enter a valid integer")
except ZeroDivisionError:
    print("Number cannot be zero")
Output

With user_input of "0", the ZeroDivisionError branch runs. With "x", ValueError runs.


Get the exception message using as e

The as e clause binds the active exception instance. Use str(e) or repr(e), or log e with the logging module. For tracebacks, use traceback.format_exc() or logger.exception(...) in real apps.

python
try:
    {}["missing"]
except (KeyError, TypeError) as e:
    print(e.__class__.__name__, "-", e)
Output

Handle different exceptions differently

When recovery differs, use separate except blocks instead of one tuple that does everything in one branch.

python
path = "/tmp/nonexistent_file_xyz.txt"
try:
    with open(path) as f:
        data = f.read()
except FileNotFoundError:
    print("create or download the file first")
except PermissionError:
    print("fix permissions on", path)
Output

Use else with try except

else runs only if the try body completes without raising. It keeps the happy path visible and avoids putting post-success logic in try where unrelated errors could be caught by the wrong handler.

python
user_input = "42"
try:
    number = int(user_input)
except ValueError:
    print("Invalid number")
else:
    print("Valid number:", number)
Output

That prints Valid number: 42. If user_input were "abc", only the except branch would run and else would be skipped.


Use finally with multiple exceptions

finally runs whether the try succeeded, an except ran, or an exception was not caught (before propagating). Use it for cleanup such as closing a file—initialize the handle to None so finally can close safely even if open never succeeded.

python
file = None
try:
    file = open("/nonexistent/path/data.txt")
    data = file.read()
except (FileNotFoundError, PermissionError) as e:
    print(e)
finally:
    if file is not None:
        file.close()
    print("cleanup ran")

cleanup always runs; file.close() runs only when open returned a file object.


Catch multiple exceptions inside a loop

Handle errors per iteration so one bad item does not stop the whole loop. Use specific exception types, not a bare except.

python
values = [2, 0, "x", 4]
for item in values:
    try:
        print(10 / int(item))
    except ZeroDivisionError:
        print("skip: divide by zero for", item)
    except ValueError:
        print("skip: not an integer:", item)
Output

Each iteration is independent; only the failing shape triggers its handler.


Should you catch all exceptions?

  • except SomeSpecificError: — preferred for predictable failures you can handle.
  • except Exception as e: — catches most application errors; still lets KeyboardInterrupt and SystemExit propagate in typical code (they inherit BaseException, not Exception). Use when you must wrap a large block and re-raise or log after cleanup.
  • except BaseException: — rarely needed in apps; includes SystemExit and KeyboardInterrupt.
  • except: (bare) — avoid; it masks bugs and interrupts, and hides the exception type.

If you catch broadly, log and re-raise or narrow the scope so you do not swallow programming mistakes.


Common mistakes when catching multiple exceptions

  • Using bare except: (no exception type), which catches almost everything and makes failures hard to diagnose.
  • Catching Exception (or a tuple of broad types) too high in the stack, turning real bugs into silent handled paths.
  • Ordering except Exception before except ValueError, so the specific handler never runs—put narrow types first.
  • Assuming every line in try runs; after the first raise, remaining lines in that try are skipped until handlers finish.
  • Using one message or one recovery path for errors that need different user actions (use separate except clauses).
  • Swallowing the error with pass or a vague print—prefer logging or re-raising after wrapping so the original message or traceback is preserved.

Python multiple exceptions quick reference table

Pattern Syntax
Several types, one handler except (A, B, C) as e:
Different handlers except A: ... then except B: ...
Bind instance except ValueError as e:
Run if no exception try: ... except ...: ... else: ...
Always cleanup try: ... finally: ...
Safe file cleanup f = None / try: f = open(...) / finally: close if f

Summary

You can catch multiple exception types with except (Type1, Type2): when one response fits all, or with stacked except clauses when behavior should differ. as e gives you the instance for logging or messages. else marks code that runs only on success inside the try, and finally guarantees cleanup. In loops, wrap each iteration so failures are isolated. Prefer specific types, order handlers from narrow to broad, avoid bare except, and remember only the first exception in a try body is raised for that attempt—plan examples and production code accordingly.


References


Frequently Asked Questions

1. How do you catch more than one exception type in a single except in Python?

Put the exception types in a parenthesized tuple after except, for example except (ValueError, TypeError) as e: so any of those types is handled by the same block.

2. Does Python run every line in a try block after one line raises?

No; when an exception is raised, execution jumps to the matching except immediately, so later lines in the same try block are skipped until the handler finishes and execution continues after the full try/except/else/finally construct.

3. What is the difference between except Exception and a bare except?

except Exception catches most built-in errors you care about but not system-exit style events; a bare except also catches BaseException subclasses like KeyboardInterrupt and SystemExit and makes bugs harder to find, so avoid bare except in application code.

4. When should I use else with try except in Python?

Use else on a try when you want code to run only if the try block completed without raising an exception, which keeps the try body focused on the operation that might fail.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …