Raising Exceptions
Python · Exception Handling
Theory
raise lets your own code signal an error. raise ValueError('Salary cannot be negative') creates an exception object with a message and throws it; the current function stops at once and Python looks for a matching except up the call stack. If nothing catches it, the program stops and prints the message in the traceback.
Choose a built-in type that describes the problem: ValueError for a bad value, TypeError for a wrong type, KeyError for a missing key. For business-specific errors you can define your own class, class InsufficientBalanceError(Exception): pass, and raise it. Inside an except block, a bare raise re-raises the current exception after you log it, and raise NewError(...) from e wraps it while keeping the original cause in the traceback.
Why we use it
Failing fast with a clear message is better than letting bad data flow on silently. raise lets functions enforce their rules - no negative salary, no empty file - and tell the caller exactly what went wrong.
When to use it
Raise when a function gets input it cannot handle or a business rule is broken. Do not raise for normal, expected outcomes (like 'no rows found'); returning an empty result is usually better there.
How it works
- Call set_salary(-100)
- Is value < 0? Yes: raise ValueError('Salary cannot be negative'). No: Return the value normally.
- Function stops; Python searches for a handler
- Does a caller catch ValueError? Yes: Handle it, e.g. print(e). No: Program stops with a traceback.
- Clear error message shown
Syntax
raise ExceptionType("message")Example
def set_salary(value):
if value < 0:
raise ValueError("Salary cannot be negative")
return value
try:
set_salary(-100)
except ValueError as e:
print(e)Key points
- Lets you enforce business rules with clear, specific errors
- Custom exception classes can extend Exception for domain-specific errors
- Pick a meaningful built-in type: ValueError, TypeError, KeyError
- A bare raise inside except re-raises the current exception
- raise New(...) from e keeps the original cause