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

