Python
raise keyword
error handling
exceptions
programming tips

How to use raise keyword in Python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

The raise keyword is how Python signals that execution cannot continue normally. Used well, it makes function contracts clearer and failures easier to debug. Used badly, it creates vague errors, hides root causes, or turns normal control flow into exception-heavy code.

Raise Specific Exceptions

The first rule is to raise an exception type that matches the failure. Standard exception classes already cover many common cases.

python
1def require_non_empty(text: str) -> str:
2    if not text:
3        raise ValueError("text must not be empty")
4    return text
5
6
7def set_port(port: int) -> None:
8    if not isinstance(port, int):
9        raise TypeError("port must be an int")
10    if not 1 <= port <= 65535:
11        raise ValueError("port out of range")

Use TypeError for wrong types, ValueError for bad values, KeyError for missing mapping keys, and so on. A precise exception tells the caller what kind of mistake happened before they even read the message.

Define Custom Exceptions for Domain Logic

For business rules, custom exception classes make the code easier to understand and easier to catch selectively.

python
1class BillingError(Exception):
2    pass
3
4
5class InsufficientFunds(BillingError):
6    pass
7
8
9def charge(balance: float, amount: float) -> float:
10    if amount <= 0:
11        raise ValueError("amount must be positive")
12    if balance < amount:
13        raise InsufficientFunds("balance is too low for this charge")
14    return balance - amount

Now callers can catch BillingError without swallowing unrelated runtime failures. That is much better than raising plain Exception everywhere.

Use raise ... from to Preserve the Cause

Sometimes you catch a low-level exception and want to replace it with a clearer higher-level one. When you do that, keep the original cause.

python
1def parse_port(raw: str) -> int:
2    try:
3        port = int(raw)
4    except ValueError as exc:
5        raise ValueError("port must be an integer") from exc
6
7    if not 1 <= port <= 65535:
8        raise ValueError("port out of range")
9    return port

The from exc part preserves the exception chain. That makes tracebacks much more informative in logs and production incidents. Without it, the original parsing failure disappears and you lose useful debugging context.

Re-Raise the Current Exception When You Only Need Cleanup

Inside an except block, plain raise means "throw the same exception again." That is the right choice when you need to log, count metrics, or clean up resources without changing the error itself.

python
1def read_config(path: str) -> str:
2    try:
3        with open(path, "r", encoding="utf-8") as file_handle:
4            return file_handle.read()
5    except OSError:
6        print("config read failed")
7        raise

Compare that with raise NewError(...), which replaces the current exception. Replacing every exception automatically is usually a mistake because it throws away detail that the caller or log reader may need.

Raise at Boundaries, Not in Every Tiny Branch

Good exception design usually validates bad input near the system boundary, then lets the rest of the code assume valid data. That is cleaner than scattering raise checks through every internal loop.

For example:

  • validate API request data when it first enters the service
  • validate file format after parsing, not deep in business logic
  • raise immediately when invariants are broken

This style keeps the error contract easy to reason about. It also reduces the chance of invalid values leaking deeper into the program and failing in confusing ways later.

Test Exception Behavior Explicitly

Exception behavior is part of a function's public contract, so it should be tested like any other output.

python
1import pytest
2
3
4def must_be_even(n: int) -> None:
5    if n % 2:
6        raise ValueError("n must be even")
7
8
9def test_must_be_even_raises() -> None:
10    with pytest.raises(ValueError, match="even"):
11        must_be_even(3)

Testing the exception type and part of the message makes it harder for regressions to slip through unnoticed.

When Not to Use raise

Exceptions are for exceptional or invalid states, not for everyday branching in performance-sensitive code. If a missing value is a normal case, returning None, an empty list, or a typed result object may be clearer than raising an exception. Overusing exceptions for routine control flow makes the code noisy and harder to profile.

That does not mean exceptions are expensive in every practical sense. It means they should communicate failure, not replace basic boolean logic.

Common Pitfalls

The biggest mistake is raising generic Exception for everything. Another is replacing a low-level exception with a new one and forgetting from, which destroys the causal chain. Developers also catch exceptions too broadly and then continue as if nothing happened, which hides bugs instead of handling them. Finally, some code uses exceptions as ordinary branching logic, which makes intent less clear and error handling harder to test.

Summary

  • Raise specific exception types that match the failure.
  • Use custom exception classes for domain-specific rules.
  • Preserve original causes with raise ... from.
  • Use plain raise to rethrow the current exception after cleanup or logging.
  • Treat exception behavior as part of the function contract and test it explicitly.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.