- Learning Objectives
- Prerequisites
- Introduction
- What is Raising an Exception?
- Why Raise Exceptions?
- The raise Keyword
- Syntax
- Built-in Exceptions
- Custom Error Messages
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand the
raisekeyword. - Learn when and why exceptions should be raised.
- Raise built-in exceptions manually.
- Create meaningful exception messages.
- Understand how exception propagation works.
- Write robust and maintainable Python programs.
Before learning this chapter, you should know:
- Exception Handling
- try Block
- except Block
- else Block
- finally Block
In the previous chapters,
we learned how to handle exceptions after they occur.
Sometimes,
a program must detect an invalid condition and immediately stop normal execution.
For example,
a Banking Application should not allow a withdrawal amount greater than the available balance.
Instead of allowing incorrect operations,
the program should raise an exception.
Python provides the
raisekeyword for this purpose.
Raising an Exception means creating an exception intentionally when an invalid condition is detected during program execution.
Instead of waiting for Python to generate an exception automatically,
the programmer explicitly raises the exception.
Raising an exception means generating an exception manually using the
raisekeyword.
Suppose we are developing an ATM Application.
Current Balance
₹5,000
User Requests
Withdraw ₹10,000
Without validation,
the transaction may continue incorrectly.
Instead,
the application should raise an exception such as
Insufficient Balance
and stop the transaction.
The raise keyword is commonly used in:
- Banking Applications
- E-Commerce Websites
- Login Systems
- Payment Gateways
- Hospital Management Systems
- Student Management Systems
- Inventory Applications
- API Development
The raise keyword is used to generate an exception manually.
Syntax
raise ExceptionTypeExample
raise ValueErroror
raise ValueError("Invalid Input")raise ValueError("Invalid Age")raise TypeError("Only Integer Values Allowed")raise ZeroDivisionError("Cannot Divide by Zero")raise RuntimeError("Unexpected Runtime Error")| Exception | Used When |
|---|---|
| ValueError | Invalid value supplied |
| TypeError | Wrong data type |
| ZeroDivisionError | Division by zero |
| IndexError | Invalid index |
| KeyError | Invalid dictionary key |
| FileNotFoundError | Missing file |
| PermissionError | Permission denied |
| RuntimeError | General runtime issue |
Every exception can include a custom message.
Example
raise ValueError("Age must be greater than 18.")Output
ValueError:
Age must be greater than 18.
Meaningful error messages make debugging easier.
When an exception is raised,
Python searches for the nearest matching
exceptblock.
If a matching handler exists,
the exception is handled.
Otherwise,
the program terminates and displays a traceback.
Program Executes
↓
Condition Checked
↓
Condition Invalid?
↓
No
↓
Continue Program
------------------------
Yes
↓
raise Statement Executes
↓
Exception Object Created
↓
Search Matching except Block
↓
Found?
↓
Yes
↓
Handle Exception
↓
Continue Program
------------------------
No
↓
Program Terminates
- Detects invalid conditions early.
- Prevents incorrect program execution.
- Improves code reliability.
- Produces meaningful error messages.
- Simplifies debugging.
- Helps enforce business rules.
- Raise specific exceptions instead of generic ones.
- Write meaningful exception messages.
- Raise exceptions only for exceptional situations.
- Validate input before processing.
- Keep business rules clear and consistent.
Raising a generic exception unnecessarily.
Prefer
raise ValueError(...)instead of
raise Exception(...)when a more specific exception applies.
Using vague error messages.
Poor example
raise ValueError("Error")Better example
raise ValueError("Age must be greater than or equal to 18.")Using raise for normal program flow.
Exceptions should represent exceptional situations,
not ordinary control flow.
The raise keyword is used to generate an exception manually.
To detect invalid conditions and stop incorrect program execution.
Yes.
Python allows built-in exceptions such as ValueError, TypeError, and RuntimeError to be raised manually.
Yes.
Custom messages can be passed while raising an exception.
Python searches for the nearest matching except block.
If none is found,
the program terminates with a traceback.
raisegenerates an exception manually.- Use specific exception classes.
- Provide meaningful error messages.
- Exceptions represent abnormal situations.
- Python searches for a matching
exceptblock after an exception is raised.
In this chapter, you learned:
- Raising Exceptions
raiseKeyword- Built-in Exceptions
- Custom Error Messages
- Exception Propagation
- Internal Working
- Advantages
- Best Practices
- Common Mistakes
- Interview Questions
- Quick Revision
Write a Python program to raise a ValueError when the age is less than 18.
age = int(input("Enter Age : "))
if age < 18:
raise ValueError("Age must be at least 18.")
print("Eligible")Enter Age : 15
ValueError: Age must be at least 18.
If the age is less than 18,
the program raises a ValueError manually.
try:
age = int(input("Enter Age : "))
if age < 18:
raise ValueError("Age must be at least 18.")
print("Eligible")
except ValueError as error:
print(error)Enter Age : 16
Age must be at least 18.
The exception is raised using raise
and handled using the except block.
number = "100"
if not isinstance(number, int):
raise TypeError("Only integer values are allowed.")TypeError: Only integer values are allowed.
The program validates the data type before processing.
server_status = False
if not server_status:
raise RuntimeError("Server is currently unavailable.")RuntimeError: Server is currently unavailable.
RuntimeError is raised for unexpected runtime conditions.
balance = 5000
withdraw = int(input("Enter Amount : "))
if withdraw > balance:
raise ValueError("Insufficient Balance.")
balance -= withdraw
print("Remaining Balance :", balance)Enter Amount : 7000
ValueError: Insufficient Balance.
Business rules are enforced by raising an exception.
marks = int(input("Enter Marks : "))
if marks < 0 or marks > 100:
raise ValueError("Marks must be between 0 and 100.")
print("Valid Marks")Enter Marks : 120
ValueError: Marks must be between 0 and 100.
Input validation ensures only valid marks are accepted.
salary = int(input("Enter Salary : "))
if salary < 0:
raise ValueError("Salary cannot be negative.")
print("Salary Accepted")Enter Salary : -5000
ValueError: Salary cannot be negative.
password = input("Enter Password : ")
if len(password) < 8:
raise ValueError("Password must contain at least 8 characters.")
print("Password Accepted")Enter Password : admin
ValueError: Password must contain at least 8 characters.
The program validates password length before accepting it.
quantity = int(input("Enter Quantity : "))
if quantity <= 0:
raise ValueError("Quantity must be greater than zero.")
print("Order Accepted")Enter Quantity : 0
ValueError: Quantity must be greater than zero.
Invalid order quantities are rejected using an exception.
try:
amount = int(input("Enter Amount : "))
if amount > 100000:
raise ValueError("Transaction limit exceeded.")
print("Transaction Successful")
except ValueError as error:
print(error)Enter Amount : 150000
Transaction limit exceeded.
The business rule is enforced using raise
and handled gracefully using try-except.
Program Starts
↓
Input Accepted
↓
Condition Checked
↓
Condition Valid?
↓
Yes
↓
Continue Program
------------------------
No
↓
raise Statement
↓
Exception Object Created
↓
Matching except Block
↓
Handle Exception
↓
Program Continues
Program
↓
Input Value
↓
Validation
↓
Valid?
↓
Yes
↓
Continue
------------------------
No
↓
raise
↓
Exception Object
↓
except Block
↓
Program Continues
- Detects invalid input early.
- Prevents incorrect program execution.
- Improves software reliability.
- Enforces business rules.
- Produces meaningful error messages.
- Raise specific exceptions.
- Write meaningful error messages.
- Validate data before processing.
- Handle raised exceptions where appropriate.
- Avoid raising exceptions for normal program flow.
Using generic exceptions unnecessarily.
❌ Incorrect
raise Exception("Invalid Input")✅ Better
raise ValueError("Age must be at least 18.")Raising exceptions without meaningful messages.
Always explain why the exception occurred.
Using exceptions instead of proper validation logic.
Validate inputs first and raise exceptions only when validation fails.
Ignoring raised exceptions.
If an exception is expected,
handle it appropriately using try-except.
The raise keyword is used to generate an exception manually.
To indicate invalid conditions and prevent incorrect program execution.
Yes.
Exceptions such as ValueError, TypeError, and RuntimeError can be raised manually.
Yes.
A custom message can be passed while raising the exception.
Python searches for the nearest matching except block.
If none is found,
the program terminates with a traceback.
No.
It should only be used for exceptional situations.
ValueError.
- Raise a
ValueErrorfor invalid age. - Raise a
TypeErrorfor invalid data types. - Validate student marks using
raise. - Validate password length.
- Create a banking withdrawal validation program.
raisemanually generates exceptions.- Use specific exception classes.
- Write meaningful error messages.
- Validate data before processing.
- Handle exceptions using
try-except.
In this chapter, we learned:
raiseKeyword- Raising Built-in Exceptions
- Custom Error Messages
- Business Rule Validation
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision