π Day 91/150 – Custom Exceptions in Python
Python provides many built-in exceptions like ValueError, TypeError, and ZeroDivisionError. But sometimes you may need to create your own exception to represent specific errors in your program. This is called a custom exception.
In this post, we'll learn four ways to work with custom exceptions in Python.
Method 1 – Creating a Basic Custom Exception
Create your own exception by inheriting from the built-in Exception class.
class AgeError(Exception): pass age = int(input("Enter your age: ")) if age < 18: raise AgeError("You must be at least 18 years old.") print("Access Granted!")
Sample Input
16Output
AgeError: You must be at least 18 years old.
Explanation
- AgeError is a custom exception class.
- raise is used to manually trigger the exception.
- If the age is less than 18, Python raises AgeError.
Method 2 – Handling a Custom Exception
You can catch your custom exception using try and except.
class AgeError(Exception):
15pass try: age = int(input("Enter your age: ")) if age < 18: raise AgeError("You must be at least 18 years old.") print("Access Granted!") except AgeError as error: print(error)
Sample Input
Output
You must be at least 18 years old.Explanation
- The custom exception is raised inside the try block.
- The except block catches AgeError.
- The program continues instead of crashing.
Method 3 – Custom Exception with a Custom Message
You can define your own message inside the exception class.
class NegativeNumberError(Exception): def __init__(self): super().__init__("Negative numbers are not allowed.") num = int(input("Enter a number: ")) if num < 0: raise NegativeNumberError() print("Valid Number")
Sample Input
-8
Output
Negative numbers are not allowed.
Explanation
- The constructor (__init__) defines a default error message.
- Whenever the exception is raised, the message is displayed automatically.
Method 4 – Custom Exception in a Function
Custom exceptions are commonly used inside functions.
class PasswordError(Exception): pass def check_password(password): if len(password) < 8: raise PasswordError("Password must contain at least 8 characters.") return "Password Accepted" try: print(check_password(input("Enter password: "))) except PasswordError as error: print(error)
Sample Input
pythonOutput
Password must contain at least 8 characters.Explanation
- The function checks the password length.
- If the password is too short, it raises a custom exception.
- The exception is caught outside the function using try and except.
Comparison of Methods
| Method | Best Used For |
|---|---|
| Basic Custom Exception | Creating your own exception type |
| Custom Exception with try/except | Handling custom errors gracefully |
| Custom Message | Providing meaningful error messages |
| Function-based Exception | Validating function inputs |
π₯ Key Takeaways
- A custom exception is a user-defined exception created by inheriting from the Exception class.
- Use the raise keyword to trigger a custom exception.
- Catch custom exceptions using try and except.
- Custom exceptions make your programs easier to understand and debug.
- They are useful for validating user input and enforcing application-specific rules.
- Giving custom exceptions meaningful names and messages makes your code more readable.


0 Comments:
Post a Comment