raise statement
raise stops normal execution by throwing an exception, so bad input or impossible situations are reported instead of ignored.
raise ExceptionType("message")
raise
raise NewError("message") from original_errorraise creates an error on purpose. The function stops at once and the exception travels up to whoever called it, until a try / except / else / finally block catches it or the program ends with a message.
Raise an error when your code is given something it cannot work with: a negative age, an empty order, a missing setting. Failing loudly early is much easier to debug than a wrong result later.
Pick a built-in type that fits (ValueError for a bad value, TypeError for the wrong type) or make your own by subclassing Exception. Inside an except block, a plain raise re-throws the error you just caught.
Examples
1Reject bad input
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
print(set_age(30))
try:
set_age(-5)
except ValueError as e:
print("Error:", e)30 Error: age cannot be negative
2Your own exception class
class PaymentError(Exception):
pass
def pay(balance, amount):
if amount > balance:
raise PaymentError(f"need {amount}, have only {balance}")
return balance - amount
try:
pay(20, 35)
except PaymentError as e:
print("Payment failed:", e)Payment failed: need 35, have only 20
3Re-raise after logging
A plain raise inside except sends the same error on, after you have done something with it.
def read_setting(settings, key):
try:
return settings[key]
except KeyError:
print("log: setting", key, "is missing")
raise
try:
read_setting({"theme": "dark"}, "language")
except KeyError:
print("The caller handles it")log: setting language is missing The caller handles it
4Chain errors with from
def parse_price(text):
try:
return float(text)
except ValueError as e:
raise RuntimeError(f"bad price: {text!r}") from e
try:
parse_price("12,50")
except RuntimeError as e:
print(e)
print("caused by:", type(e.__cause__).__name__)bad price: '12,50' caused by: ValueError
from e keeps the original error attached, so a traceback would show both.
Common mistakes
Raising a string
raise "something went wrong" is a TypeError: only exception objects can be raised. Wrap the message: raise ValueError("something went wrong").
try:
raise "oops"
except TypeError:
print("TypeError: you can only raise exceptions")TypeError: you can only raise exceptions
Using a too general exception type
raise Exception(...) forces callers to catch everything. A specific type, such as ValueError or your own class, lets them catch exactly this problem.
Questions people ask
What is the difference between raise and return?
return ends a function normally with a result. raise ends it with an error that the caller must handle.
How do I create a custom exception?
Subclass Exception: class InvalidOrder(Exception): pass, then raise InvalidOrder("empty basket").
raise vs assert?
assert statement is for checks during development that should never fail and can be switched off. Use raise to report real problems with input.