🟢 Beginner · Lesson 18
Exception Handling
Exception क्या है?
Exception वह error है जो program चलते समय आती है (जैसे zero से भाग)। handle न करने पर program crash हो जाता है। Exception handling आपको error पकड़कर शालीनता से जवाब देने देता है।
try / except
Python – tryexcept
try:
# risky code
risky_operation()
except SomeError:
# वह error होने पर चलता है
handle_it()Python try block आज़माता है। error आने पर crash के बजाय matching except पर कूद जाता है।
Common Errors
| Error | कारण |
|---|---|
| ZeroDivisionError | 0 से भाग |
| ValueError | int("abc") — गलत type की value |
| TypeError | "5" + 5 — types मिलाना |
| FileNotFoundError | न मौजूद file खोलना |
| IndexError | List index out of range |
Program 1: Safe Division
Python – divide.py
a = int(input("Numerator: "))
b = int(input("Denominator: "))
try:
print("Result:", a / b)
except ZeroDivisionError:
print("Error: cannot divide by zero")Numerator: 10
Denominator: 0
Error: cannot divide by zero
try के बिना 0 से भाग program crash कर देता। अब यह friendly message print करता है।
Program 2: Safe Number Input
Python – safeinput.py
try:
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
except ValueError:
print("Please enter a valid number")Enter your age: hello
Please enter a valid number
User number की जगह text type करे तो int() ValueError देता है, जिसे हम पकड़ते हैं।
Program 3: कई except + finally
Python – multi.py
try:
nums = [10, 20, 30]
i = int(input("Index: "))
print(nums[i])
except ValueError:
print("Index must be a number")
except IndexError:
print("Index out of range")
finally:
print("Done checking")Index: 5
Index out of range
Done checking
- हर
exceptअलग error type handle करता है। finallyहमेशा चलता है — error हो या न हो — cleanup के लिए अच्छा।
अपना Error Raise करना
Input गलत होने पर खुद error देने के लिए raise use करें।
Python – raise.py
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
print("Age set to", age)
try:
set_age(-5)
except ValueError as e:
print("Caught:", e)Caught: Age cannot be negative
सामान्य गलतियाँ
- bare
except:से हर error पकड़ना — असली bugs छुपा देता है। - एक
tryblock में बहुत ज़्यादा code डालना। - यह भूलना कि
finallyहर हाल में चलता है।
Practice Tasks
- दो numbers पूछकर safely divide करें।
- तब तक number पूछते रहें जब तक user valid न दे।
- File खोलकर FileNotFoundError अच्छे से handle करें।
- एक function लिखें जो negative marks पर error raise करे।
सारांश
- Exceptions runtime errors हैं; handling crashes रोकता है।
tryrisky code चलाता है;exceptspecific errors पकड़ता है।finallyहमेशा चलता है;raiseअपना error बनाता है।
💻 लाइव कोड एडिटर
इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.