Introduction
In Python, you can raise custom exceptions to handle specific situations in your program that aren’t covered by the built-in exceptions. Custom exceptions allow you to define and manage errors specific to your application’s logic. This is done by creating a new exception class that inherits from Python’s built-in Exception
class or one of its subclasses.
This tutorial will guide you through creating a Python program that demonstrates how to define and raise custom exceptions.
Example:
- Custom Exception:
InvalidAgeError
- Condition: The age entered must be between 0 and 120.
- Program Output:
Entered age is not valid.
Problem Statement
Create a Python program that:
- Defines a custom exception named
InvalidAgeError
. - Raises this exception if the age entered by the user is not between 0 and 120.
- Catches and handles the custom exception, printing an appropriate error message.
Solution Steps
- Define the Custom Exception: Create a class named
InvalidAgeError
that inherits from theException
class. - Prompt for Input: Use the
input()
function to get the user’s age. - Check the Condition: Use an
if
statement to check if the age is within the valid range. - Raise the Custom Exception: If the age is not valid, raise the
InvalidAgeError
exception. - Handle the Exception: Use a
try-except
block to catch the custom exception and print an error message.
Python Program
# Python Program to Raise Custom Exceptions
# Author: https://www.rameshfadatare.com/
# Step 1: Define the Custom Exception
class InvalidAgeError(Exception):
def __init__(self, age, message="Entered age is not valid."):
self.age = age
self.message = message
super().__init__(self.message)
# Step 2: Prompt for Input
try:
age = int(input("Enter your age: "))
# Step 3: Check the Condition
if age < 0 or age > 120:
# Step 4: Raise the Custom Exception
raise InvalidAgeError(age)
else:
print(f"Age {age} is valid.")
# Step 5: Handle the Exception
except InvalidAgeError as e:
print(f"Error: {e.message} (Age: {e.age})")
except ValueError:
print("Error: Please enter a valid integer for age.")
Explanation
Step 1: Define the Custom Exception
- The
InvalidAgeError
class is defined as a custom exception by inheriting from Python’s built-inException
class. The__init__
method initializes the exception with the providedage
and a custommessage
. It then calls the__init__
method of the parentException
class usingsuper()
.
Step 2: Prompt for Input
- The program prompts the user to input their age using the
input()
function. The input is converted to an integer usingint()
.
Step 3: Check the Condition
- An
if
statement checks whether the entered age is within the valid range of 0 to 120.
Step 4: Raise the Custom Exception
- If the age is not within the valid range, the
InvalidAgeError
custom exception is raised using theraise
statement, passing theage
as an argument.
Step 5: Handle the Exception
- The
try-except
block catches theInvalidAgeError
exception. When caught, it prints an error message along with the invalid age. - Additionally, a
ValueError
is caught to handle cases where the user inputs a non-integer value for age.
Output Example
Example Output 1: Valid Age
Enter your age: 25
Age 25 is valid.
Example Output 2: Invalid Age (Too High)
Enter your age: 150
Error: Entered age is not valid. (Age: 150)
Example Output 3: Invalid Input (Non-Integer)
Enter your age: abc
Error: Please enter a valid integer for age.
Additional Examples
Example 1: Custom Exception for Invalid Salary
class InvalidSalaryError(Exception):
def __init__(self, salary, message="Entered salary is not valid."):
self.salary = salary
self.message = message
super().__init__(self.message)
try:
salary = float(input("Enter your salary: "))
if salary < 0:
raise InvalidSalaryError(salary)
else:
print(f"Salary {salary} is valid.")
except InvalidSalaryError as e:
print(f"Error: {e.message} (Salary: {e.salary})")
except ValueError:
print("Error: Please enter a valid number for salary.")
Output:
Enter your salary: -5000
Error: Entered salary is not valid. (Salary: -5000.0)
Example 2: Custom Exception for Invalid Product Code
class InvalidProductCodeError(Exception):
def __init__(self, code, message="Invalid product code."):
self.code = code
self.message = message
super().__init__(self.message)
try:
code = input("Enter the product code: ")
if not code.startswith("P") or len(code) != 5:
raise InvalidProductCodeError(code)
else:
print(f"Product code {code} is valid.")
except InvalidProductCodeError as e:
print(f"Error: {e.message} (Code: {e.code})")
Output:
Enter the product code: 12345
Error: Invalid product code. (Code: 12345)
Example 3: Raising Multiple Custom Exceptions
class InvalidUsernameError(Exception):
def __init__(self, username, message="Username is invalid."):
self.username = username
self.message = message
super().__init__(self.message)
class InvalidPasswordError(Exception):
def __init__(self, password, message="Password is invalid."):
self.password = password
self.message = message
super().__init__(self.message)
try:
username = input("Enter username: ")
password = input("Enter password: ")
if len(username) < 5:
raise InvalidUsernameError(username)
if len(password) < 8:
raise InvalidPasswordError(password)
print("Username and password are valid.")
except InvalidUsernameError as e:
print(f"Error: {e.message} (Username: {e.username})")
except InvalidPasswordError as e:
print(f"Error: {e.message} (Password: {e.password})")
Output:
Enter username: user
Enter password: pass
Error: Username is invalid. (Username: user)
Conclusion
This Python program demonstrates how to define and raise custom exceptions to handle specific errors that aren’t covered by Python’s built-in exceptions. By using custom exceptions, you can create more robust and maintainable code that clearly communicates issues specific to your application’s logic. Understanding how to raise and handle custom exceptions is a valuable skill in Python programming.