Python raise: Raise Your Own Exceptions
What Does raise Do in Python?
The raise statement makes an exception happen on purpose. You use it when a value is wrong for your program, even though Python itself sees no problem with it.
age = -5
if age < 0:
raise ValueError("Age can't be negative")
print("Age saved")ValueError: Age can't be negative
To Python, -5 is a perfectly good number. But you know that nobody is minus five years old. raise stops the program right there, with your own message, before the bad value can cause trouble later.
Think of it like a referee's whistle. The players may not notice the foul, but the referee does, blows the whistle, and play stops.
How to write it
raise, then the error type, then your message in brackets:
raise ValueError("Marks must be 0 to 100")
The rules
- A raised error behaves exactly like Python's own: the program stops, unless an
exceptcatches it. - The message is a string. Say what's wrong, and what's allowed.
- Pick the error type that fits the problem:
| Problem | Type to raise | Example message |
|---|---|---|
| the right kind of value, but a bad one | ValueError | "Marks must be 0 to 100" |
| the wrong kind of value | TypeError | "Price must be a number" |
ValueError is the one you'll raise most: a negative age, marks over 100, an empty name.
Good messages
marks = 150
if marks < 0 or marks > 100:
raise ValueError(f"Marks must be 0 to 100, not {marks}")ValueError: Marks must be 0 to 100, not 150
An f-string (chapter 5) puts the bad value into the message, so whoever reads it sees exactly what went wrong. Compare that to a message like "Error", which tells you nothing.
raise ErrorType("message") stops the program on purpose when a value makes no sense.