How can I write a try/except block that catches all Python exceptions?

It is a general thumb rule that though you can catch all exceptions using code like below, you shouldn't ?

try:
    # do_something()
    pass
except:
    print("Exception Caught!")

However, this will also catch exceptions like KeyboardInterrupt and SystemExit that we may not be interested in handling. This can make it difficult to interrupt your program or cause other unexpected behaviors.

Better Approach with Exception Re-raising

A better approach is to catch all exceptions but re-raise them after logging or handling. Here's a complete example ?

import sys

try:
    f = open('file.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as e:
    print("I/O error: {0}".format(e))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

The output of the above code is ?

I/O error: [Errno 2] No such file or directory: 'file.txt'

Using Exception as Base Class

If you specifically want to catch all Python exceptions while avoiding system-level exceptions, use Exception as the base class ?

try:
    # Some risky operation
    result = 10 / 0
except Exception as e:
    print(f"Caught an exception: {e}")
    print(f"Exception type: {type(e).__name__}")

The output of the above code is ?

Caught an exception: division by zero
Exception type: ZeroDivisionError

This approach catches all exceptions that inherit from Exception but allows KeyboardInterrupt and SystemExit to pass through normally.

Conclusion

While catching all exceptions is possible, it's better to be specific about which exceptions you handle. When you must catch all exceptions, use except Exception rather than bare except to avoid catching system exits and keyboard interrupts.

Updated on: 2026-03-13T17:46:05+05:30

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements