Python Exception Handling
Real programs me invalid input, missing data aur unexpected situations aa sakti hain. Exception handling se program ko controlled way me failure handle karna, useful message dena aur cleanup karna sikhte hain.
Errors and exceptions
Syntax errors code parse hone se pehle problem batate hain, while exceptions usually program run hote waqt raise hoti hain. Examples: ValueError, TypeError, ZeroDivisionError, KeyError and FileNotFoundError.
number = int("hello")
print(number)Syntax valid hai, lekin "hello" ko integer me convert nahi kiya ja sakta. Isliye runtime par ValueError raise hota hai.
Basic try/except
Risky operation ko try block me rakho aur expected failure ko matching except block me handle karo.
try:
age = int(input("Enter age: "))
print(f"Age: {age}")
except ValueError:
print("Please enter a whole number.")Catch specific exceptions
Specific exception catch karne se real bugs accidentally hide nahi hote. Broad except Exception: kabhi-kabhi boundary layers par useful ho sakta hai, but beginner logic me exact expected errors better hain.
try:
total = float(input("Total: "))
count = int(input("Count: "))
print(total / count)
except ValueError:
print("Numbers only, please.")
except ZeroDivisionError:
print("Count cannot be zero.")Multiple exception types
Same recovery action ho to exception types ko tuple me group kar sakte ho.
data = {"score": "88"}
try:
score = int(data["score"])
except (KeyError, ValueError) as error:
print(f"Invalid score data: {error}")as error exception object deta hai. User-facing applications me raw internal error details unnecessarily expose mat karo.
try/except/else
else tab run hota hai jab try block me exception raise nahi hoti. Isse protected code ko minimum rakhna easy hota hai.
try:
score = int("92")
except ValueError:
print("Invalid score")
else:
print(f"Valid score: {score}")finally always gets a chance to run
finally block normally success ya handled/unhandled exception ke baad cleanup ke liye run hota hai.
print("Start")
try:
value = 10 / 2
print(value)
finally:
print("Cleanup step")with) often manual cleanup se clearer hote hain. File handling Chapter 15 me detail me aayega.Full try/except/else/finally flow
try:
number = int(input("Number: "))
except ValueError:
print("Invalid integer")
else:
print(f"Double: {number * 2}")
finally:
print("Operation finished")Raise your own exception
Program rule violate hone par raise se meaningful exception create kar sakte ho.
def set_percentage(value):
if not 0 <= value <= 100:
raise ValueError("percentage must be between 0 and 100")
return value
print(set_percentage(85))Invalid state ko silently accept karne se better hai clear failure create karna, especially reusable functions me.
Re-raise an exception
Exception ko log/additional context dene ke baad same exception propagate karna ho to bare raise current handler ke andar use hota hai.
try:
value = int("bad")
except ValueError:
print("Conversion failed")
raiseHar exception ko forcefully swallow karna correct recovery nahi hota. Kabhi caller ko failure know karna zaroori hota hai.
Custom exceptions
Domain-specific error ko clearly represent karne ke liye Exception subclass bana sakte ho.
class InvalidMarksError(Exception):
pass
def validate_marks(mark):
if not 0 <= mark <= 100:
raise InvalidMarksError("mark must be 0 to 100")
return mark
try:
validate_marks(120)
except InvalidMarksError as error:
print(error)Custom exception tab useful hoti hai jab caller ko generic ValueError se zyada domain-specific distinction chahiye.
Exception chaining with raise ... from ...
Low-level failure ko higher-level meaning me convert karte waqt original cause preserve karna useful hai.
def parse_score(text):
try:
return int(text)
except ValueError as error:
raise ValueError("score must be a whole number") from errorfrom error traceback me causal relationship preserve karta hai, jo debugging me helpful hota hai.
Exception hierarchy — beginner view
Most application exceptions Exception ke descendants hoti hain. Bare except: broader BaseException family ko catch kar sakta hai, including signals such as KeyboardInterrupt and SystemExit. Isliye normal application code me bare except avoid karo.
Read the traceback
Unhandled exception ka traceback sirf error message nahi hota; ye call path, file/line information aur exception type deta hai. Debugging ke waqt bottom se exception type/message dekho, phir relevant stack frames trace karo.
assert is not normal input validation
def average(marks):
assert marks, "developer assumption: marks must not be empty"
return sum(marks) / len(marks)assert developer assumptions/debugging ke liye useful hai, but external user input validation ya essential business rules ke replacement ke roop me use mat karo. Python optimization modes assertions remove kar sakte hain.
EAFP style — ask forgiveness, not permission
Python code me kabhi direct operation try karke expected exception handle karna natural hota hai. Lekin exceptions ko normal loop control ya avoidable mistakes hide karne ke liye overuse mat karo.
student = {"name": "Aman"}
try:
print(student["score"])
except KeyError:
print("Score not available")Practical validation pattern
def read_mark(text):
mark = float(text)
if not 0 <= mark <= 100:
raise ValueError("mark must be between 0 and 100")
return mark
samples = ["85", "hello", "120"]
for sample in samples:
try:
mark = read_mark(sample)
except ValueError as error:
print(f"{sample!r}: invalid ({error})")
else:
print(f"{sample!r}: accepted as {mark}")Common beginner mistakes
- Bare
except:laga kar every failure hide kar dena. - Huge
tryblock me unrelated code rakhna. - Wrong exception type catch karna.
except Exception:ke andar error silently ignore karna.- Exception message ko user validation ka only source bana dena.
finallymereturnuse karke earlier exception/result accidentally override karna.- Expected invalid input ke liye crash hone dena jab recovery simple ho.
- Programming bug ko user error samajh kar suppress kar dena.
- Custom exception ko unnecessarily complex banana.
assertko production input validation samajhna.
Beginner best practices
- Only expected exceptions catch karo.
tryblock ko narrow rakho.- Recovery possible ho tab recover karo; otherwise failure propagate hone do.
- Clear, actionable error messages do.
- Reusable function me invalid arguments ke liye appropriate exception raise karo.
- Cleanup ke liye
finallyya appropriate context manager use karo. - Debugging ke liye traceback read karna habit banao.
- Sensitive internal details end user ko expose mat karo.
Chapter checklist
- Syntax error aur runtime exception ka difference clear hai?
try/exceptse expected failure handle kar sakte ho?- Multiple specific exception handlers likh sakte ho?
elseaurfinallyka role samajh aaya?raisese validation error create kar sakte ho?- Custom exception subclass banana samajh aaya?
- Bare except avoid karne ka reason clear hai?
- Traceback se exception type identify kar sakte ho?
Practice Task — Safe Student Result Processor
BrounStack Playground me exception-safe result processor banao.
- Student name input lo.
- Three subject marks input lo.
- String marks ko
floatme convert karo. - Conversion failure par
ValueErrorhandle karo. - 0–100 range ke bahar mark ho to manually
ValueErrorraise karo. - Valid marks list me store karo.
- Average calculate karo.
- Empty valid-data case safely handle karo.
- Grade return karne ke liye function banao.
- At least one
elseblock use karo. - One
finallyblock me completion message print karo. - One custom
InvalidMarksErrorversion bhi try karo. - Bare
except:use mat karo. - Deliberately invalid input dekar recovery test karo.