Raising Exceptions in Python
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.
raise ExceptionType("message")
Creates and immediately triggers a new exception, with a descriptive message.
Execution stops right there
Any code between the raise and the nearest matching except stops running immediately.
A bare raise re-raises the current exception
Used inside an except block, with no arguments, to pass it along unchanged.
Choose a specific, appropriate exception type
ValueError, TypeError, and so on — this helps callers catch and handle it correctly.
Custom exceptions raise the same way
Covered in a later topic, for errors specific to a particular program.
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}")Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.