Skip to content

Module 12 · Exception Handling — topic 9 of 11

Raising exceptions

Signalling errors from your own code with raise: choosing the right exception type and message, re-raising with bare raise, chaining with raise ... from, and validating arguments early.

Beginner 10 min read·Lesson 191 of 306 in Python Programming

Learning objectives

  • Raise built-in exceptions with clear messages
  • Re-raise after logging
  • Chain exceptions with raise ... from

Definition

The raise statement throws an exception: raise ValueError('message'). A bare raise inside an except block re-raises the current exception, and raise NewError(...) from err links a new exception to its cause.

Introduction

Your functions have rules too: an age can't be negative, a quantity must be positive. When the rules are broken, raising an exception tells the caller clearly and immediately.

Why it matters

Returning special values like -1 or None for errors is easy to ignore. An exception can't be ignored silently, and it carries a message explaining what went wrong.

Detailed explanation

raise ExceptionType('message') creates and raises an exception. Pick the type that matches the problem: ValueError for bad values, TypeError for wrong types, KeyError/LookupError for missing items.

Write messages that help the caller fix the problem: include the bad value and the rule, e.g. 'age cannot be negative: -3'.

Guard clauses validate arguments at the start of a function and raise early, before any work is done.

Inside an except block, a bare raise re-raises the current exception with its original traceback — useful after logging or partial cleanup.

raise NewError('...') from original links the two exceptions: the new one's __cause__ is the original, and tracebacks show both. Use it when translating low-level errors into meaningful ones.

raise ... from None hides the original when it would only confuse the reader.

You can raise exception classes or instances; raise ValueError is the same as raise ValueError().

Syntax

Python
def set_age(age):
if age < 0:
raise ValueError(f"age cannot be negative: {age}")
...
try:
...
except KeyError as e:
raise ConfigError("missing setting") from e
  • raise Type(message).
  • Bare raise re-raises.
  • from links cause and effect.

Code examples

Validating an argument

Python
def set_age(age):
if age < 0:
raise ValueError(f"age cannot be negative: {age}")
return age
print(set_age(25))
try:
set_age(-3)
except ValueError as e:
print(e)
Output
25
age cannot be negative: -3

Logging then re-raising

Python
def parse(text):
try:
return int(text)
except ValueError:
print("logging bad input:", text)
raise
try:
parse("abc")
except ValueError as e:
print("caller sees:", type(e).__name__)
Output
logging bad input: abc
caller sees: ValueError

More examples

Translating errors with raise ... from

Python
class ConfigError(Exception):
pass
def read_port(settings):
try:
return int(settings["port"])
except (KeyError, ValueError) as e:
raise ConfigError("port setting is missing or invalid") from e
for s in [{"port": "8080"}, {"port": "eighty"}, {}]:
try:
print("port", read_port(s))
except ConfigError as e:
print(f"{e} (cause: {type(e.__cause__).__name__}: {e.__cause__})")
Output
port 8080
port setting is missing or invalid (cause: ValueError: invalid literal for int() with base 10: 'eighty')
port setting is missing or invalid (cause: KeyError: 'port')

Step-by-step explanation

  • Callers of read_port only need to know about ConfigError, not about dictionaries or int().
  • from e stores the original exception in __cause__.
  • The handler can still show the underlying reason for debugging.

Expected output

Running “Translating errors with raise ... from” prints exactly:

TextOutput
port 8080
port setting is missing or invalid (cause: ValueError: invalid literal for int() with base 10: 'eighty')
port setting is missing or invalid (cause: KeyError: 'port')

Practical applications

  • Libraries raise their own errors (requests.HTTPError) chained from lower-level ones.
  • Functions validating arguments before writing to a database.

Best practices

  • Validate early and raise with specific messages.
  • Use the most appropriate built-in type or a custom one.
  • Chain translated errors with from.

Common mistakes

Raising a generic Exception

Avoid

raise Exception("bad")

Prefer

raise ValueError("quantity must be positive, got 0")

Callers can't catch a precise type, and the message gives no detail.

raise e instead of raise

Avoid

except ValueError as e:
log(e)
raise e

Prefer

except ValueError:
log(...)
raise

Bare raise is the clearer idiom for re-raising the current exception.

Important notes

  • assert statements also raise (AssertionError) but can be disabled with -O; don't use them for input validation.

Key takeaways

  • raise signals an error from your code.
  • Bare raise re-raises the current exception.
  • raise ... from links a new error to its cause.

Try it yourself

  1. 1
    Write withdraw(balance, amount) that raises ValueError for non-positive amounts and for insufficient funds.
  2. 2
    Translate a FileNotFoundError into a SettingsError using raise ... from.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this topic