Python Exception vs BaseException: Key Differences
Understand the key differences between Python's Exception and BaseException classes, when to catch each, and why catching BaseException can intercept KeyboardInterrupt or SystemExit.

When you write a try/except block in Python, the choice between Exception and BaseException controls which runtime failures your code handles and which ones it lets propagate. The practical rule is simple: catch Exception for ordinary program errors, and do not catch BaseException unless you specifically need to intercept control-flow signals such as KeyboardInterrupt or SystemExit.
The Python Exception Hierarchy
Python's exception classes form a tree rooted at BaseException. Every built-in exception, from SyntaxError to KeyboardInterrupt, inherits directly or indirectly from that root. The Exception class is a subclass of BaseException and is the base for most exceptions that represent ordinary runtime problems.
BaseException
├── GeneratorExit
├── KeyboardInterrupt
├── SystemExit
└── Exception
├── ArithmeticError
├── AssertionError
├── AttributeError
├── EOFError
├── ImportError
├── LookupError
├── NameError
├── OSError
├── RuntimeError
├── SyntaxError
├── TypeError
├── ValueError
└── ...The split matters because BaseException includes conditions that normal application code usually should not handle. SystemExit is raised when sys.exit() is called, and KeyboardInterrupt is raised when the user presses Ctrl+C. These are control-flow signals rather than errors in the program's logic.
Catching Exception vs BaseException
A bare except: clause catches every subclass of BaseException, including SystemExit and KeyboardInterrupt. In contrast, except Exception: catches only subclasses of Exception, leaving the system-level exceptions untouched.
try:
risky_operation()
except Exception:
# This does not catch KeyboardInterrupt or SystemExit
handle_error()try:
risky_operation()
except BaseException:
# This catches everything, including KeyboardInterrupt and SystemExit
handle_error()The second pattern is rarely what you want. If a user presses Ctrl+C during a long-running operation, catching BaseException prevents the KeyboardInterrupt from propagating, so the program cannot be interrupted normally. Similarly, catching SystemExit can break a script that relies on sys.exit() to terminate with a specific exit code.
Why You Should Usually Catch Exception
For most error-handling code, except Exception is a safer default than except BaseException. It covers the exceptions that represent recoverable problems: missing files, invalid input, network failures, and so on. It deliberately excludes SystemExit, KeyboardInterrupt, and GeneratorExit, which are not errors in the same sense.
Consider a function that reads a configuration file. If the file is missing, you want to fall back to defaults. Catching Exception handles FileNotFoundError and PermissionError without interfering with shutdown behavior.
import yaml
def load_config():
try:
with open("config.yaml") as f:
return yaml.safe_load(f)
except Exception:
return {}The handler is broad, so in production code you would likely narrow it to expected I/O errors. For this discussion, the relevant point is that it still leaves KeyboardInterrupt and SystemExit alone. If a user presses Ctrl+C while the file is being read, the KeyboardInterrupt propagates, and the program stops as expected. The except Exception block does not intercept it.
When Catching BaseException Is Appropriate
Cleanup is usually better handled without catching BaseException. A finally block or a context manager runs its cleanup for any exception, including KeyboardInterrupt and SystemExit, and the original exception continues to propagate afterward.
class LockManager:
def __init__(self, lock):
self.lock = lock
def __enter__(self):
self.lock.acquire()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.lock.release()Once a with block is active, the context manager's __exit__ method is called even when a BaseException subclass is raised, so this pattern gives you cleanup without swallowing control-flow signals. It is not a case for catching BaseException in your own code.
There are still a few cases where catching BaseException is justified. One is a top-level wrapper that must log every possible termination reason before re-raising:
try:
main()
except BaseException:
log_shutdown()
raiseThe raise statement is critical. Without it, the SystemExit or KeyboardInterrupt is swallowed, and the program may hang or exit with the wrong code.
Custom Exceptions: Inherit from Exception
For normal application exceptions, inherit from Exception, not from BaseException. This makes your exceptions behave like ordinary runtime errors and ensures they are caught by except Exception handlers.
class ConfigError(Exception):
pass
class ValidationError(Exception):
passIf you inherit from BaseException directly, an except Exception block will not catch your exception. That can cause a library's broad error handling to miss it and can signal that the exception is meant for control flow, which is rarely the intent for application code. Only choose BaseException when you intentionally need that control-flow behavior, and document the choice.
Handling SystemExit and KeyboardInterrupt Explicitly
If you need to perform cleanup on SystemExit or KeyboardInterrupt, catch them explicitly rather than using a broad BaseException. This keeps your intent clear and avoids accidentally swallowing unrelated errors.
import sys
try:
main()
except KeyboardInterrupt:
print("Interrupted by user", file=sys.stderr)
sys.exit(130)
except SystemExit:
# Preserve the original exit code
raise
except Exception:
handle_regular_error()This structure handles the three categories separately. KeyboardInterrupt gets a custom exit code, SystemExit is re-raised to preserve its code, and Exception covers the rest. It is more verbose than a single except BaseException, but it is also more precise and less likely to hide bugs.
The Cost of Overly Broad Exception Handling
Catching BaseException in a library or framework can have subtle consequences. If a user's code raises SystemExit to terminate a script, and your library swallows it, the script may continue running unexpectedly. Similarly, swallowing KeyboardInterrupt makes it impossible for the user to stop a loop that is stuck in a long computation.
In a service where a termination signal is translated into SystemExit or KeyboardInterrupt, a library that catches BaseException without re-raising can prevent the process from shutting down cleanly.
A better approach is to let these exceptions propagate and use finally blocks for cleanup. The finally clause runs whether an exception is raised or not, and it does not interfere with the exception's propagation.
resource = acquire_resource()
try:
use_resource(resource)
finally:
resource.release()This guarantees cleanup without needing to catch BaseException. The finally block runs even if KeyboardInterrupt or SystemExit occurs, and the exception continues to propagate after the cleanup.
Compatibility and Maintainability
Python's exception hierarchy has remained stable for Python 3, but the exact set of BaseException subclasses can vary by version and implementation. For example, GeneratorExit is a BaseException subclass that is raised when a generator is closed. Catching it accidentally can break generator finalization. The standard rule remains: use Exception for normal error handling and reserve BaseException for the rare cases where you must intercept control-flow signals.
When reviewing code, except BaseException is a red flag unless it is accompanied by a clear comment explaining why it is necessary and a raise statement to re-raise the exception. The same applies to a bare except: clause, which is equivalent to except BaseException:.
By keeping your exception handling narrow, you make the code more predictable and easier to maintain. Future readers will understand which failures are expected and which are allowed to terminate the program.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.