Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Raising Exceptions in Python: Syntax and Usage

Learn how to use Python's raise statement to raise built-in and custom exceptions, chain errors, and preserve tracebacks.

~5 min readPython
#Python#Exceptions#Error Handling#Custom Exceptions
Python raise exception concept: a raised error signal with a traceback path

When a function encounters a condition it cannot handle, it needs a way to stop execution and communicate the failure to the caller. In Python, the raise statement is that mechanism. Using raise correctly determines whether your error handling is clear and debuggable or fragile and confusing. This article covers the syntax, common patterns, and design decisions around raising exceptions.

The Basic Syntax of raise

The simplest form of raise takes an exception instance or an exception class. When you pass a class, Python instantiates it without arguments. When you pass an instance, you can provide a custom message.

python
raise ValueError raise ValueError("invalid input")

The first form is less common because it produces an exception without a message. The second form is more common because the message is what developers see in logs and error trackers. You can also raise an exception from within an except block to replace the current exception, but that has subtle implications covered later.

Raising Built-in Exceptions with Context

Python's standard library defines many exception types that cover typical runtime problems. Choosing the right one makes your code self-documenting. For example, TypeError signals a type mismatch, ValueError signals an inappropriate value, and KeyError signals a missing dictionary key.

python
def get_user_age(user): if not isinstance(user, dict): raise TypeError("user must be a dict") if "age" not in user: raise KeyError("age field missing") age = user["age"] if age < 0: raise ValueError("age cannot be negative") return age

Each exception type communicates a different problem to the caller. The caller can catch a specific type and handle it accordingly. Using the wrong type, such as raising Exception for every failure, forces callers to rely on string matching, which is brittle.

Creating Custom Exception Classes

For application-specific failures, define a custom exception class that inherits from Exception. This allows callers to catch your domain errors without depending on built-in types that may not express the actual problem.

python
class InsufficientBalanceError(Exception): pass def withdraw(account, amount): if amount > account.balance: raise InsufficientBalanceError("available balance is lower than requested amount") account.balance -= amount

A custom exception can carry extra attributes that help with debugging. Override __init__ to store structured data, but keep the base Exception initialization intact so the message is still available.

python
class InsufficientBalanceError(Exception): def __init__(self, balance, requested): self.balance = balance self.requested = requested super().__init__(f"requested {requested}, available {balance}")

Now the exception message is human-readable, and the numeric values are accessible programmatically. This pattern is especially useful when an API consumer needs to decide how to handle the error based on the difference between the requested and available amounts.

Chaining Exceptions with from

When an exception occurs while handling another exception, Python automatically sets the new exception's __context__ to the original one. You can control this relationship explicitly with the from keyword. This is useful when you want to wrap a low-level error into a higher-level domain error without losing the original traceback.

python
def load_config(path): try: with open(path) as f: return json.load(f) except OSError as exc: raise ConfigLoadError("unable to read config file") from exc

Without from, the original exception is still attached as __context__; Python shows both exceptions in the traceback, separated by “During handling of the above exception, another exception occurred.” With from, the original is assigned to __cause__, and the traceback says the new exception was the direct cause of the failure. This makes the causal chain explicit. If you want to suppress the context entirely, use from None, but that should be reserved for cases where the original exception is irrelevant to the caller.

Re-raising Exceptions Without Losing Traceback

Sometimes you need to catch an exception, perform some cleanup or logging, and then let the same exception propagate. A bare raise inside an except block re-raises the current exception while preserving its original traceback.

python
def process_file(path): try: return parse(path) except ParseError: log_error(path) raise

Using raise ParseError(...) instead of raise would create a new exception whose own traceback starts at the new raise line. If side effects are all you need, a bare raise is the correct way to continue propagating the exact exception. If you intentionally want to raise a different exception from inside an except block, chain it with from to preserve the original context.

When Raising Exceptions Is the Right Design Choice

Raising an exception is not always the best way to communicate a problem. Exceptions are for exceptional conditions, not for normal control flow. If a function frequently expects a certain failure, returning a sentinel value or a result object may be more appropriate.

Consider a function that looks up a record by ID. If missing records are a normal occurrence, returning None might be simpler. But if missing records indicate a corrupted database or an invalid caller, raising LookupError is appropriate. The decision depends on how the caller is expected to react.

Another consideration is the cost of exceptions. Raising an exception involves building a traceback, which is relatively expensive compared to a simple return. In performance-sensitive loops, avoid using exceptions for expected conditions. For example, parsing user input that often fails validation is better handled with a validation function that returns a boolean or a list of errors, rather than raising and catching exceptions for every invalid entry.

Common Mistakes and Edge Cases

One frequent mistake is raising a new exception from inside an except block without chaining it, which replaces the original exception and makes the causal relationship less explicit.

python
try: risky_operation() except OSError as exc: raise RuntimeError("operation failed") from exc

If you replace the exception, use from exc to preserve the original as the direct cause. Another edge case is raising an exception class that is not a subclass of BaseException. Python only allows raising classes derived from BaseException; attempting to raise a plain class results in a TypeError. Also, be careful with exceptions raised by a context manager's __exit__. If __exit__ itself raises while the body of a with block is also raising, the __exit__ exception propagates and the body exception becomes its context. That can mask the original failure unless you handle it explicitly.

Finally, remember that raise can be used outside of exception handling. It is a regular statement that can appear anywhere in a function. The traceback will point to the line where the raise statement is executed, which is useful for debugging. Keep the message specific and actionable so that someone reading the traceback understands what went wrong and what input caused it.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.