Skip to content

Computer Science · Ch 1 — Exception Handling in Python

Raising Exceptions

1.5

Raising Exceptions

When a program runs into an error, the Python interpreter automatically raises (or throws) an exception. This is the normal way Python signals that something has gone wrong. But programmers are not limited to waiting for errors to happen — they can also forcefully raise exceptions in their own code using two specific statements: raise and assert.

The key idea is that raising an exception deliberately interrupts the normal flow of execution. Once an exception is raised, no further statement in the current block of code runs. Instead, control jumps to the part of the program designed to handle that exception — the exception handler. This allows a programmer to signal an error condition explicitly, even when Python itself might not detect one.

Note

Exception handlers are written to execute only when a specific exception is raised — whether by the interpreter or by the programmer.

The raise statement is the direct way to throw an exception. You can use it with a built-in exception class (like ValueError or TypeError) or with a custom exception. For example:

if age < 0:
    raise ValueError("Age cannot be negative")

The assert statement is a debugging aid. It checks a condition, and if that condition is False, it raises an AssertionError. This is useful for catching impossible situations during development:

assert x > 0, "x must be positive"

Both statements serve the same purpose — to raise an exception — but assert is typically used for internal checks that should never fail in a correct program, while raise is used for explicit error handling. …