Home Course Roadmap
Home / Python Course / Lesson 42
Lesson 42 Error Handling

Python raise

Learn how to deliberately raise exceptions in Python so your programs can validate data, enforce rules and clearly communicate invalid situations.

40–50 minutes Beginner Error Handling
0%
01

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 raise inside functions.
  • Combine raise with try / except.
  • Re-raise exceptions.
  • Create simple custom exceptions.
  • Build stronger validation logic.
02

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.

Python
raise ValueError("Something went wrong.")
Result
ValueError: Something went wrong.
Simple idea

raise means: "Stop normal execution and report this situation as an exception."

03

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.
Validation principle

When your program receives invalid data, raise allows you to stop the invalid operation and communicate the reason.

04

Basic raise Syntax

The basic form is:

Python
raise ExceptionType("message")

For example:

Python
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.

Common pattern

Choose an exception type that accurately describes the problem instead of using a random exception.

05

Raising Built-in Exceptions

Python provides many built-in exception classes that can be raised when appropriate.

Python
raise ValueError("Invalid value.")

raise TypeError("Wrong type.")

raise RuntimeError("Operation cannot continue.")

raise PermissionError("Access denied.")
Some useful exception types
  • ValueError — invalid value
  • TypeError — inappropriate type
  • RuntimeError — generic runtime problem
  • PermissionError — permission problem
  • FileNotFoundError — missing file
  • IndexError — invalid sequence index
  • KeyError — missing dictionary key
06

Raising ValueError

ValueError is commonly used when a value has the right general type but is not acceptable.

Python
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.

Result
ValueError: Age cannot be negative.
07

Raising TypeError

Use TypeError when a function receives an object of an inappropriate type.

Python
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.

Why this matters

A function can clearly communicate what kind of data it expects instead of failing later in a less understandable way.

08

Conditional Validation with raise

One of the most practical uses of raise is combining it with if statements.

Python
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.

Validation pattern

Check the condition → detect invalid data → raise an appropriate exception.

09

raise + try / except

An exception raised with raise can be caught using try / except.

Python
try:
    age = -10

    if age < 0:
        raise ValueError("Age cannot be negative.")

except ValueError as error:
    print("Validation error:", error)
Output
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.

10

Creating Useful Exception Messages

A custom message makes an exception much easier to understand.

Python
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.

Good exception messages should explain:
  • What went wrong.
  • Which value caused the problem.
  • What rule was violated.
  • When useful, what value was expected.
11

Using raise Inside Functions

Functions often use raise to protect their assumptions and validate arguments.

Python
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))
Output
50

Now try an invalid value:

Python
print(calculate_area(-10, 5))
Function contract

A function can use exceptions to clearly communicate that the caller supplied invalid arguments.

12

Input Validation

raise becomes particularly useful when validating user input after converting it into the appropriate type.

Python
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.
This is an important programming concept.

Valid data is not simply data that has the correct type. It must also satisfy the rules of the application.

13

Real-World Examples

Example 1 — E-commerce Price

Python
def set_price(price):

    if price < 0:
        raise ValueError("Product price cannot be negative.")

    return price


print(set_price(2500))

Example 2 — Student Marks

Python
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

Python
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)
Output
Remaining balance: 700
14

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.

Python
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.")
Output
Logging validation problem.
Caller handled the exception.
Why re-raise?

A lower-level function can record information or perform local processing while allowing higher-level code to make the final decision.

15

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.

Python
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.

Why create custom exceptions?

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.

16

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.

Good rule

Raise an exception when an operation cannot reasonably continue under the current conditions.

17

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.

18

Mini Challenge — Student Registration Validator

Build a validation function for a student registration system.

Your function should validate:
  • 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

Python
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)
Challenge extension

Add email validation, a minimum age requirement for different courses, and a rule that prevents duplicate student registrations.

19

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?

20

Lesson Summary

In this lesson, you learned how to deliberately raise exceptions using Python's raise statement.

raise deliberately triggers an exception.
Built-in exceptions such as ValueError and TypeError can be raised directly.
raise is extremely useful for validation.
Custom exception messages make problems easier to understand.
Raised exceptions can be caught using try / except.
Exceptions can be raised inside functions to enforce argument rules.
A bare raise can re-raise the current exception.
Custom exception classes are useful for application-specific errors.
Key takeaway

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.