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.
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
- raise Type(message).
- Bare raise re-raises.
- from links cause and effect.
Code examples
Validating an argument
25 age cannot be negative: -3
Logging then re-raising
logging bad input: abc caller sees: ValueError
More examples
Translating errors with raise ... from
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:
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
Prefer
Callers can't catch a precise type, and the message gives no detail.
raise e instead of raise
Avoid
Prefer
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
- 1Write withdraw(balance, amount) that raises ValueError for non-positive amounts and for insufficient funds.
- 2Translate 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?