User Defined Exception in Python
Theory
In Python, an exception is an error that occurs during program execution and interrupts the normal flow of the program.
Sometimes the built-in exceptions are not enough for a program. In such cases, programmers can create their own exceptions called User Defined Exceptions.
A user defined exception is created by defining a new class that inherits from the Exception class.
This helps programmers handle custom errors based on specific conditions in the program.
Syntax
class ExceptionName(Exception):
pass
Basic Example Program
# User Defined Exception Example
class AgeError(Exception):
pass
age = int(input("Enter your age: "))
try:
if age < 18:
raise AgeError
else:
print("You are eligible to vote")
except AgeError:
print("Error: Age must be 18 or above")
Sample Output
Case 1
Enter your age: 20
You are eligible to vote
Case 2
Enter your age: 15
Error: Age must be 18 or above
Explanation
-
class AgeError(Exception)→ Creates a user defined exception -
raise AgeError→ Raises the custom exception -
tryblock → Contains risky code -
exceptblock → Handles the error
✅ Conclusion:
User defined exceptions allow programmers to create custom error handling mechanisms, making programs more controlled and reliable.
- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
Comments
Post a Comment