0
0
PythonDebug / FixBeginner · 3 min read

How to Handle Multiple Exceptions in Python: Simple Guide

In Python, you can handle multiple exceptions by listing them as a tuple inside a single except block, like except (TypeError, ValueError):. This lets you catch different errors together and respond to them in one place.
🔍

Why This Happens

When you try to catch multiple exceptions but write separate except blocks without proper handling, your code can become repetitive or miss some errors. Also, if you try to catch multiple exceptions incorrectly, Python will raise a syntax error.

python
try:
    x = int('hello')
except TypeError, ValueError:
    print('Caught an error')
Output
File "<stdin>", line 3 except TypeError, ValueError: ^ SyntaxError: invalid syntax
🔧

The Fix

Use a tuple to list multiple exceptions inside one except block. This way, Python knows to catch any of those exceptions and run the same code. This keeps your code clean and easy to read.

python
try:
    x = int('hello')
except (TypeError, ValueError):
    print('Caught a TypeError or ValueError')
Output
Caught a TypeError or ValueError
🛡️

Prevention

Always group related exceptions using a tuple in one except block when you want to handle them the same way. Use separate except blocks only if you want different handling for each error. Also, test your code to make sure all expected exceptions are caught.

Using linters like flake8 or pylint can help catch syntax mistakes early. Writing clear comments about which exceptions you expect improves code readability.

⚠️

Related Errors

Sometimes developers confuse catching multiple exceptions with catching all exceptions using a bare except:, which is not recommended because it hides unexpected errors. Also, catching exceptions incorrectly by using commas instead of tuples causes syntax errors.

python
try:
    x = int('hello')
except:
    print('Caught any error')
Output
Caught any error

Key Takeaways

Use a tuple in except to catch multiple exceptions together.
Separate except blocks only if you need different handling for each error.
Avoid bare except: as it catches all errors and can hide bugs.
Use linters to catch syntax errors early.
Write clear comments about expected exceptions for better code clarity.