liveBook · Manning

Raise statement

As explained in The Quick Python Book, Fourth Edition

A raise statement explicitly signals an exception during program execution, optionally supplying an exception instance or class.

A raise statement explicitly signals an exception during Python program execution. It interrupts the normal next-statement flow and sends the exception up the current call chain until a suitable handler catches it; without one, the program terminates or reports an error. section 14.2 section 14.1.2

Use the statement with these practical rules:

  • Write `raise exception(args)` to create an exception and throw it upward through the stack. section 14.2.2
  • Pass arguments that help explain what happened; many built-in exception classes display a first string argument as their message. section 14.2.2
  • Choose a handler with `try` and `except` when the raised condition should be handled locally; `else` and `finally` can organize successful and final processing. section 3.4.7
  • Treat exception arguments as class-specific: programmer-defined exception types may expect data other than a text message. section 14.2.2

Raise a custom condition

class EmptyFileError(Exception): pass if line == "": raise EmptyFileError("empty file") The surrounding `except EmptyFileError as error` clause can catch the exception and print its message. This makes a condition detected by application code follow the same handling path as exceptions raised by built-in operations. section 3.4.7

raise exception(args)

Inspect the compact syntax before comparing it with a concrete `IndexError` raised explicitly by code. section 14.2.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines construction, message arguments, propagation, and handling, but defers broader exception-class design.
Examples
Uses an explicit IndexError, list-index failure, and EmptyFileError raised while processing files.
What it assumes
Assumes general programming knowledge while introducing Python's exception objects, raising terminology, and handler propagation.
What you can do after
Apply it via Python to report detected conditions and route them to matching exception handlers.
How it connects
Connects exception handling with try-except-else-finally, exception classes, call stacks, and EAFP error handling.

Also explained in

Compare how 2 books explain raise statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.