Raising and Re-raising Exceptions
Use raise to signal errors and re-raise for propagation.
Introduction
The raise keyword lets you signal errors explicitly. Re-raising preserves the original error context.
raise Built-in Exception
raise ValueError('message') immediately raises that exception type with the given message.
def divide(a, b):
if b == 0:
raise ValueError('Denominator cannot be zero')
return a / b
try:
divide(5, 0)
except ValueError as e:
print(e)All lessons in this course
- Understanding Exceptions
- try / except / else / finally
- Raising and Re-raising Exceptions
- Custom Exception Classes