0
0
Pythonprogramming~5 mins

Raising exceptions in Python

Choose your learning style9 modes available
Introduction

Raising exceptions lets your program stop and show an error when something unexpected happens. It helps you catch problems early and handle them properly.

When a function gets a wrong input and can't continue.
When a file your program needs is missing or unreadable.
When a calculation results in an invalid value.
When you want to stop the program with a clear error message.
When you want to create your own error types for special cases.
Syntax
Python
raise ExceptionType("Error message")

You use the raise keyword followed by an exception type and an optional message.

The message helps explain what went wrong.

Examples
This stops the program and says the input was invalid.
Python
raise ValueError("Invalid input")
This raises a general error with a message.
Python
raise RuntimeError("Something went wrong")
This raises the base exception with your message.
Python
raise Exception("Custom error message")
Sample Program

This program checks if the age is valid. If the age is negative, it raises a ValueError. The try-except block catches the error and prints a friendly message.

Python
def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    elif age < 18:
        print("You are a minor.")
    else:
        print("You are an adult.")

try:
    check_age(-5)
except ValueError as e:
    print(f"Error: {e}")
OutputSuccess
Important Notes

Raising exceptions stops the current code and jumps to the nearest error handler.

You can create your own exception classes by inheriting from Exception.

Always provide clear messages to help understand the problem.

Summary

Use raise to stop the program when something goes wrong.

Exceptions help you find and fix errors early.

Catch raised exceptions with try-except to handle errors gracefully.