Python raise
Learn how to deliberately raise exceptions in Python so your programs can validate data, enforce rules and clearly communicate invalid situations.
Learning Objectives
By the end of this lesson, you will understand how
to deliberately create exceptions using Python's
raise statement.
You will learn how to:
- Understand the purpose of
raise. - Raise built-in exceptions.
- Attach custom messages to exceptions.
- Validate user input with
raise. - Use
raiseinside functions. - Combine
raisewithtry / except. - Re-raise exceptions.
- Create simple custom exceptions.
- Build stronger validation logic.
What Is raise?
Python's raise statement allows you to
deliberately trigger an exception.
Normally, an exception occurs because something went
wrong during execution. With raise, you
can decide that a particular condition should be
treated as an error.
raise ValueError("Something went wrong.")
ValueError: Something went wrong.
raise means:
"Stop normal execution and report this
situation as an exception."
Why Use raise?
Many programs have rules that values must follow. When a value violates one of those rules, you may want to stop the current operation.
For example:
- A person's age cannot be negative.
- A product price cannot be below zero.
- A password may need a minimum length.
- A withdrawal cannot exceed an account balance.
- A required name cannot be empty.
- A percentage should stay within an expected range.
When your program receives invalid data,
raise allows you to stop the
invalid operation and communicate the reason.
Basic raise Syntax
The basic form is:
raise ExceptionType("message")
For example:
raise ValueError("Age must be a valid number.")
The exception type tells Python what kind of problem occurred, while the message explains the specific reason.
Choose an exception type that accurately describes the problem instead of using a random exception.
Raising Built-in Exceptions
Python provides many built-in exception classes that can be raised when appropriate.
raise ValueError("Invalid value.")
raise TypeError("Wrong type.")
raise RuntimeError("Operation cannot continue.")
raise PermissionError("Access denied.")
ValueError— invalid valueTypeError— inappropriate typeRuntimeError— generic runtime problemPermissionError— permission problemFileNotFoundError— missing fileIndexError— invalid sequence indexKeyError— missing dictionary key
Raising ValueError
ValueError is commonly used when a value
has the right general type but is not acceptable.
age = -5
if age < 0:
raise ValueError("Age cannot be negative.")
print("Age:", age)
The program detects the invalid condition and deliberately raises an exception.
ValueError: Age cannot be negative.
Raising TypeError
Use TypeError when a function receives
an object of an inappropriate type.
def calculate_discount(price):
if not isinstance(price, (int, float)):
raise TypeError("Price must be a number.")
return price * 0.90
Here, isinstance() checks the type before
the calculation is performed.
A function can clearly communicate what kind of data it expects instead of failing later in a less understandable way.
Conditional Validation with raise
One of the most practical uses of raise
is combining it with if statements.
marks = 125
if marks < 0 or marks > 100:
raise ValueError("Marks must be between 0 and 100.")
print("Valid marks.")
This creates a clear business rule: marks must be between 0 and 100.
Check the condition → detect invalid data → raise an appropriate exception.
raise + try / except
An exception raised with raise can be
caught using try / except.
try:
age = -10
if age < 0:
raise ValueError("Age cannot be negative.")
except ValueError as error:
print("Validation error:", error)
Validation error: Age cannot be negative.
This pattern is powerful because one part of your program can detect and raise a problem while another part decides how to handle it.
Creating Useful Exception Messages
A custom message makes an exception much easier to understand.
balance = 500
withdrawal = 800
if withdrawal > balance:
raise ValueError(
f"Insufficient balance. Available: {balance}"
)
Because the message contains useful information, developers can understand the problem much faster.
- What went wrong.
- Which value caused the problem.
- What rule was violated.
- When useful, what value was expected.
Using raise Inside Functions
Functions often use raise to protect
their assumptions and validate arguments.
def calculate_area(width, height):
if width < 0 or height < 0:
raise ValueError(
"Width and height must be non-negative."
)
return width * height
print(calculate_area(10, 5))
50
Now try an invalid value:
print(calculate_area(-10, 5))
A function can use exceptions to clearly communicate that the caller supplied invalid arguments.
Input Validation
raise becomes particularly useful when
validating user input after converting it into the
appropriate type.
try:
age = int(input("Enter your age: "))
if age < 0 or age > 120:
raise ValueError("Age must be between 0 and 120.")
except ValueError as error:
print("Invalid input:", error)
else:
print("Your age is:", age)
Notice the difference between two types of failure:
-
Conversion failure:
int()cannot convert the input. - Validation failure: the value converts successfully but violates the application's rules.
Valid data is not simply data that has the correct type. It must also satisfy the rules of the application.
Real-World Examples
Example 1 — E-commerce Price
def set_price(price):
if price < 0:
raise ValueError("Product price cannot be negative.")
return price
print(set_price(2500))
Example 2 — Student Marks
def validate_marks(marks):
if marks < 0 or marks > 100:
raise ValueError("Marks must be between 0 and 100.")
return marks
print(validate_marks(85))
Example 3 — Bank Withdrawal
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("Withdrawal must be greater than zero.")
if amount > balance:
raise ValueError("Insufficient balance.")
return balance - amount
new_balance = withdraw(1000, 300)
print("Remaining balance:", new_balance)
Remaining balance: 700
Re-Raising Exceptions
Sometimes a function needs to perform some work when an exception occurs but still allow the exception to continue to the calling code.
Inside an except block, writing
raise without an exception re-raises
the current exception.
def process_number():
try:
number = int("abc")
return number
except ValueError:
print("Logging validation problem.")
raise
try:
process_number()
except ValueError:
print("Caller handled the exception.")
Logging validation problem. Caller handled the exception.
A lower-level function can record information or perform local processing while allowing higher-level code to make the final decision.
Creating Custom Exceptions
Python also allows developers to create their own exception classes.
Custom exceptions become especially useful in larger applications because they allow related errors to have meaningful names.
class InsufficientBalanceError(Exception):
pass
balance = 500
withdrawal = 800
if withdrawal > balance:
raise InsufficientBalanceError(
"Not enough money in the account."
)
The custom exception inherits from Python's
Exception class.
They make domain-specific errors easier to identify and handle in larger programs.
You will explore custom exceptions in greater depth later as your Python skills become more advanced.
Common raise Mistakes
1. Raising the Wrong Exception
Choose an exception type that accurately describes the problem.
2. Using Exceptions for Normal Decisions
Do not raise exceptions for ordinary situations that can be handled naturally with conditions.
3. Using Vague Messages
Messages such as "Error" provide very
little information.
4. Forgetting to Handle the Exception
If you deliberately raise an exception and nobody handles it, the program may terminate with a traceback.
5. Overusing Custom Exceptions
Custom exceptions are useful, but simple problems can often be represented using Python's built-in exception types.
Raise an exception when an operation cannot reasonably continue under the current conditions.
Practice Exercises
Try these exercises yourself before looking at a possible solution.
Exercise 1 — Positive Number
Create a function that raises
ValueError if the supplied number
is negative.
Exercise 2 — Valid Marks
Write a function that accepts marks only between 0 and 100.
Exercise 3 — Product Price
Raise an exception if a product price is zero or negative.
Exercise 4 — Password Length
Raise ValueError if a password
contains fewer than 8 characters.
Exercise 5 — Type Validation
Create a function that raises
TypeError if the supplied value
is not a number.
Exercise 6 — Bank Withdrawal
Raise an exception when the withdrawal amount exceeds the account balance.
Exercise 7 — Catch Your Own Exception
Raise a ValueError inside a
try block and catch it using
except.
Exercise 8 — Re-Raise
Create a function that catches an exception, prints a logging message, and then re-raises it.
Mini Challenge — Student Registration Validator
Build a validation function for a student registration system.
- Student name must not be empty.
- Age must be between 5 and 100.
- Marks must be between 0 and 100.
- Marks must be numeric.
- Invalid values should raise meaningful exceptions.
Starter Structure
def register_student(name, age, marks):
if not name.strip():
raise ValueError("Student name cannot be empty.")
if not isinstance(age, int):
raise TypeError("Age must be an integer.")
if age < 5 or age > 100:
raise ValueError("Age must be between 5 and 100.")
if not isinstance(marks, (int, float)):
raise TypeError("Marks must be numeric.")
if marks < 0 or marks > 100:
raise ValueError("Marks must be between 0 and 100.")
return "Student registered successfully."
try:
message = register_student(
"Ali",
20,
85
)
print(message)
except (ValueError, TypeError) as error:
print("Registration failed:", error)
Add email validation, a minimum age requirement for different courses, and a rule that prevents duplicate student registrations.
Quick Knowledge Check
Test your understanding of the
raise statement.
1. What does raise do?
2. Which exception is commonly used for an invalid value?
3. Which exception is appropriate for an inappropriate type?
4. Can an exception raised with raise be caught?
5. What is a good reason to use raise?
6. What does bare raise inside an except block do?
7. Why are custom exception classes useful?
8. What should a good exception message provide?
9. Where is raise commonly used?
10. What is the purpose of re-raising an exception?
Lesson Summary
In this lesson, you learned how to deliberately raise
exceptions using Python's raise statement.
raise deliberately triggers
an exception.
ValueError and
TypeError can be raised directly.
raise is extremely useful for
validation.
try / except.
raise can re-raise the
current exception.
try / except teaches Python how
to respond to an exception, while
raise allows your program to
decide when a condition should become an
exception. Together, they form an important
foundation for building reliable applications.
You've reached the end!
You now know how to deliberately raise exceptions, validate data, communicate problems and re-raise exceptions when necessary.