Advanced Error Handling

Robust programs likhne ke liye exceptions ka use seekhein

1. Basic Try/Except

try:
    x = int("abc")
except ValueError:
    print("Invalid input!")

Output:

Invalid input!

2. Catching Multiple Exceptions

try:
    num = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid number!")

Output:

Cannot divide by zero!

3. Using Else Block

else block sirf tab run hota hai jab koi exception nahi aata.

try:
    num = int("123")
except ValueError:
    print("Invalid input")
else:
    print("Success! Number =", num)

Output:

Success! Number = 123

4. Using Finally Block

finally block hamesha run hota hai, chahe error aaye ya na aaye.

try:
    f = open("data.txt", "w")
    f.write("Hello")
except Exception as e:
    print("Error:", e)
finally:
    f.close()
    print("File closed")

Output:

File closed

5. Raising Exceptions

Kabhi kabhi hume khud exceptions raise karna padta hai.

def withdraw(amount):
    if amount > 5000:
        raise ValueError("Amount exceeds limit!")
    else:
        print("Withdraw successful:", amount)

withdraw(6000)

Output:

ValueError: Amount exceeds limit!

6. Custom Exceptions

Hum apne khud ke exception classes bana sakte hain.

class NegativeNumberError(Exception):
    pass

def square_root(n):
    if n < 0:
        raise NegativeNumberError("Negative numbers not allowed!")
    return n ** 0.5

try:
    print(square_root(-9))
except NegativeNumberError as e:
    print("Error:", e)

Output:

Error: Negative numbers not allowed!

Summary