Learn Python
>>> exception_handling.raise

Raising Exceptions in Python

#concept

The raise statement deliberately triggers an exception, either one of Python's built-in exception types or a custom one, at the exact point a problem is detected. It's how a function signals to its caller that something has gone wrong, rather than returning an invalid or misleading result silently.

#how it works
1

raise ExceptionType("message")

Creates and immediately triggers a new exception, with a descriptive message.

2

Execution stops right there

Any code between the raise and the nearest matching except stops running immediately.

3

A bare raise re-raises the current exception

Used inside an except block, with no arguments, to pass it along unchanged.

4

Choose a specific, appropriate exception type

ValueError, TypeError, and so on — this helps callers catch and handle it correctly.

5

Custom exceptions raise the same way

Covered in a later topic, for errors specific to a particular program.

#example
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
print(f"Age set to {age}")
 
set_age(25)
 
try:
set_age(-5)
except ValueError as e:
print(f"Error: {e}")
Output
Age set to 25
Error: Age cannot be negative
1set_age(25) runs normally, since 25 is a valid age.
2set_age(-5) hits the if condition, and raise ValueError("Age cannot be negative") immediately triggers an exception, skipping the print() line entirely.
3The surrounding try/except catches that ValueError, binding it to e, and prints its message rather than letting the program crash.
#use cases
Validating a function's arguments and rejecting invalid ones clearly, instead of continuing with bad data
Signaling a specific, known failure condition to whatever code called the function
Re-raising an exception after logging it, using a bare raise inside an except block
Choosing a precise built-in exception type so callers can catch exactly the failure they're prepared to handle

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.