B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Custom Exceptions | LiveCodeProgramming

Python Custom Exceptions

In Python, you can create custom exceptions using classes to handle specific errors in your own way. They are useful when built-in exceptions are not enough.

Python में आप अपनी जरूरत के हिसाब से custom exception बना सकते हैं, ताकि special condition को handle किया जा सके।

Example 1: Create a Custom Exception

class AgeTooSmallError(Exception):
    pass

age = 15
if age < 18:
    raise AgeTooSmallError("You must be at least 18 years old.")

We created a custom exception class and used raise to trigger it.

हमने एक custom exception बनाया और raise का उपयोग करके उसे trigger किया।

Example 2: Handle Custom Exception

class SalaryTooLowError(Exception):
    def __init__(self, message):
        self.message = message

try:
    salary = 10000
    if salary < 20000:
        raise SalaryTooLowError("Salary must be at least 20000.")
except SalaryTooLowError as e:
    print("Custom Error:", e.message)

Here we defined an error message inside the custom class and used it with try-except.

हमने custom class में error message define किया और उसे try-except के साथ इस्तेमाल किया।

Example 3: Inheriting from Exception class

class InvalidAgeError(Exception):
    def __init__(self, age):
        super().__init__(f"Invalid Age: {age}. Must be 18 or older.")

def validate_age(age):
    if age < 18:
        raise InvalidAgeError(age)
    else:
        print("Access Granted")

try:
    validate_age(16)
except InvalidAgeError as err:
    print(err)

Using super(), we passed a custom message to the Exception class.

हमने super() की मदद से custom message Exception class को pass किया।