0Pricing
Python Academy · Lesson

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

  1. Understanding Exceptions
  2. try / except / else / finally
  3. Raising and Re-raising Exceptions
  4. Custom Exception Classes
← Back to Python Academy