Python Exception Handling - Complete Guide

text

1. Exception Handling Kya Hai?

Exception handling programming ka ek technique hai jise hum runtime errors ko control karne ke liye use karte hain, jise exceptions kaha jata hai. Ye errors program ko abruptly rok dete hain agar handle na kiya jaye. Python me hum exceptions ko handle karne ke liye try, except, else, aur finally blocks ka use karte hain.

2. Try-Except Block Kaise Kaam Karta Hai?

try block me wo code rakha jata hai jisme exception aane ki possibility hoti hai. Agar exception jata hai, to control turant except block me chala jata hai jahan hum error ko handle kar sakte hain. Agar exception nahi aata to except block skip hota hai.

Example:

try:
x = int(input("Koi number do: "))
result = 10 / x
print("Result =", result)
except ZeroDivisionError:
print("Error: Zero se bhaag nahi kar sakte!")
except ValueError:
print("Error: Valid number nahi diya!")
text

3. Multiple Except Blocks

Alag alag exceptions ke liye alag alag except blocks likh sakte hain:

try:
num = int(input("Number daalo: "))
print(10 / num)
except ZeroDivisionError:
print("Zero se divide nahi kar sakte.")
except ValueError:
print("Number nahi diya.")
text

4. Generic Exception Handle Karna

Agar kisi specific error ka pata nahi hai to generic except Exception as e: use kar sakte hain jisse sabhi exceptions catch ho jayenge:

try:
# risky code
except Exception as e:
print("Error aaya:", e)
text

5. Else Block

Jab try block me koi exception nahi aata to else block execute hota hai:

try:
num = int(input("Number do: "))
except ValueError:
print("Galat input!")
else:
print("Input sahi hai, number =", num)
text

6. Finally Block (Cleanup Code)

finally block aise code ke liye hota hai jo chahe exception aaye ya na aaye, hamesha run hona chahiye. Jaise file close karna:

try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File nahi mili.")
finally:
file.close()
print("File close kar diya.")
text

7. Raise Keyword (Apne Exceptions Banana)

Apne logic me bhi exceptions ko force kar sakte hain raise keyword ke zariye:

age = int(input("Age do: "))
if age < 18:
raise Exception("Sorry, age must be 18 or above.")
text

8. Custom Exception Banana

Python me apne custom exceptions class bana kar custom error messages generate kar sakte hain:

class AgeError(Exception):
pass

age = int(input("Age do: "))
if age < 18:
raise AgeError("Age should be at least 18.")
text

9. Summary

Exception handling Python programming me bahut zaroori hai kyunki ye program ko unexpected error se bachata hai aur user friendly messages dikhata hai. Isse program gracefully handle hota hai aur crash nahi karta.

Python ke try-except-else-finally blocks ko seekh kar tum apne programs ko reliable aur robust bana sakte ho.

Agar tum chaho to is page ke code ko apni website me easily link kar sakte ho taaki tumhare students ko detailed samajh aaye.