liveBook · Manning

Raise statement

As explained in Python How-To

A raise statement is Python syntax that explicitly signals an exception during program execution.

Use the Python raise statement when code must explicitly signal a problem instead of waiting for an operation to produce an exception. Raising an exception helps users understand what went wrong and handle the failure appropriately. section 12.5 section 12.5.1

Use these basic forms:

  • raise ExceptionClass raises an instance of the specified exception class; raise ValueError is syntactic sugar for raise ValueError(). section 12.5.1
  • raise ExceptionClass("custom message") attaches a concise explanation to the exception. section 12.5.1
  • Handle the raised instance with try...except when the surrounding code should respond to the failure. section 12.5.1 section 12.6

Provide a useful error message

code_used = "3#" raise ValueError(f"You used a wrong parameter: {code_used!r}") # ERROR: ValueError: You used a wrong parameter: '3#' Keep the message concise so it informs users without overwhelming them. section 12.5.1

>>> raise ValueError
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError

>>> raise ZeroDivisionError
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ZeroDivisionError

Compare the traceback produced by raising ValueError and ZeroDivisionError without custom messages. section 12.5.1

How Python How-To covers it

How deep it goes
Explains bare and parameterized forms, syntactic sugar, exception instances, and concise messages, without detailing custom-class implementation.
Examples
Uses ValueError, ZeroDivisionError, formatted parameter messages, tracebacks, and a TypeError testing challenge.
What it assumes
Assumes familiarity with Python exceptions and introduces manual raising, exception instances, and custom messages.
What you can do after
Apply it via Python syntax to signal failures and provide concise diagnostic messages.
How it connects
Connects exception classes, exception instances, custom exception classes, and try...except exception 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 Python How-To. The section links point to the parts of the book it draws on.