try, except, finally
try block mein risky code likhte ho, except block mein handle karte ho agar exception aaye. finally block HAMESHA chalta hai — chahe exception aaye ya na aaye, chahe except ne handle kiya ho ya nahi — cleanup code ke liye perfect.
Python mein specific exception types catch kar sakte ho (jaise ValueError, ZeroDivisionError, FileNotFoundError) — ye C++ ke exception types jaisa hi concept hai. Generic except: (bina type ke) sab kuch pakad leta hai, lekin usually avoid karna chahiye (bahut broad hai).
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Zero se divide nahi kar sakte!")
return None
else:
print("Successfully divided") # sirf tab chalega agar koi exception NA aaye
return result
finally:
print("Ye hamesha chalta hai") # chahe exception aaye ya na aaye
print(divide(10, 2)) # "Successfully divided", "Ye hamesha chalta hai", 5.0
print(divide(10, 0)) # "Zero se divide...", "Ye hamesha chalta hai", None- try = risky code, except = handle karo, finally = hamesha chalta hai
- Specific exception types catch karo (bare except: avoid karo)
- else clause = sirf success case mein chalta hai
Ek try block ke saath multiple except blocks ho sakte hain — alag-alag exception types ke liye alag handling. Ek except mein tuple bhi de sakte ho multiple types ek saath handle karne ke liye.
try:
value = int(input("Number daalo: "))
result = 10 / value
except ValueError:
print("Ye number nahi hai!")
except ZeroDivisionError:
print("Zero se divide nahi kar sakte!")
except (TypeError, KeyError): # multiple types ek saath
print("Type ya key error")
except Exception as e: # sabse generic, sabse last
print(f"Kuch aur error: {e}")Jab ek except block ke andar khud ek naya exception raise karna ho (original error ka context preserve karte hue), raise NewError() from original_error use karo — ye "exception chain" batata hai, debugging mein bahut helpful.
def parse_config(value):
try:
return int(value)
except ValueError as e:
raise ValueError(f"Invalid config value: {value}") from e
try:
parse_config("abc")
except ValueError as e:
print(e) # "Invalid config value: abc"
print(e.__cause__) # original ValueError bhi accessible hai