Raise
Raise
Sometimes Python creates errors for you.
But sometimes you should create an error when data is wrong.
Python gives us raise for this.
What Is raise?
raise lets you stop the program and create an exception manually.
You use it when something should not be allowed.
Why raise Matters
It helps you:
- Validate data
- Stop bad input
- Protect your program
- Show clear error messages
Basic Structure
raise ErrorType("message")
Example: Negative Age
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Result
Python shows an error message because the value is not allowed.
Example: Password Too Short
password = "123"
if len(password) < 6:
raise ValueError("Password too short")
Example: Use raise with try
try:
score = int(input("Enter score: "))
if score < 0 or score > 100:
raise ValueError("Score must be between 0 and 100")
print("Valid score")
except ValueError as error:
print(error)
Example Output
Enter score: 120
Score must be between 0 and 100
Common Error Types to Raise
ValueErrorTypeErrorZeroDivisionErrorException
Usually ValueError is great for bad user input.
Why Not Only Use if?
An if can check rules.
raise adds a real error that can be caught and handled.
This is useful in larger programs and functions.
Example: Function Validation
def set_price(price):
if price < 0:
raise ValueError("Price cannot be negative")
print("Saved")
set_price(10)
Output
Saved
Code Along
Build a username checker.
Rules:
- Name cannot be empty
- If empty, raise an error
Mini Challenge
Build a ticket checker.
Steps:
- Ask for age
- Convert to number
- If age is below
0, raise an error - If age is valid, print:
Ticket allowed
- Handle the error with
try/except
Expected output:
Enter age: -1
Age cannot be negative
Real World Use Case
Programs use raise in forms, payments, APIs, login systems, and business rules.
Quiz
- What does
raisedo? - Why use
raise? - Which error type is common for bad input?
- Can raised errors be caught with
try/except?
Assignment
Create a function that accepts a number. Raise an error if the number is less than 1.
Summary
You learned how to create your own errors using raise to protect your program and validate data.