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

Raise Exceptions in Python

In Python, we can manually raise exceptions using the raise keyword. It is useful when we want to stop the program and show an error if a specific condition is not met.

Python में हम raise keyword का उपयोग करके manually error (exception) throw कर सकते हैं। यह तब उपयोगी होता है जब किसी condition पर error दिखाना हो।

Example 1: Raise ValueError

age = -5
if age < 0:
    raise ValueError("Age cannot be negative")

This raises an error if the age is invalid (negative).

अगर age negative है तो error raise किया जाएगा।

Example 2: Raise TypeError

x = "50"
if not isinstance(x, int):
    raise TypeError("Only integers are allowed")

Raises error if the variable is not of type integer.

अगर variable integer नहीं है तो TypeError raise किया जाता है।

Example 3: Use raise inside try-except

try:
    raise ZeroDivisionError("Division by zero is not allowed")
except ZeroDivisionError as e:
    print("Caught error:", e)

You can raise and catch exceptions inside try-except blocks.

आप try-except block के अंदर भी raise और handle कर सकते हैं।

Example 4: Raise Custom Exception

class InvalidAgeError(Exception):
    pass

def set_age(age):
    if age < 0:
        raise InvalidAgeError("Age cannot be negative")
    else:
        print("Age is:", age)

set_age(-1)

You can create your own exception class by inheriting from Exception.

आप अपनी custom exception class भी बना सकते हैं।