LearningPython TutorialException Handling
CHAPTER 14 · ROBUST PROGRAMS

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.

English + Hinglish64 min readOnline practice included

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.

runtime-error.pyPython
number = int("hello")
print(number)
Hinglish Explanation

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.

basic.pyPython
try:
    age = int(input("Enter age: "))
    print(f"Age: {age}")
except ValueError:
    print("Please enter a whole number.")

Try invalid input →

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.

specific.pyPython
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.

multiple.pyPython
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.

else.pyPython
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.

finally.pyPython
print("Start")
try:
    value = 10 / 2
    print(value)
finally:
    print("Cleanup step")
Design note: Files and many resources ke liye context managers (with) often manual cleanup se clearer hote hain. File handling Chapter 15 me detail me aayega.

Full try/except/else/finally flow

full-flow.pyPython
try:
    number = int(input("Number: "))
except ValueError:
    print("Invalid integer")
else:
    print(f"Double: {number * 2}")
finally:
    print("Operation finished")

Run full flow →

Raise your own exception

Program rule violate hone par raise se meaningful exception create kar sakte ho.

raise.pyPython
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.

reraise.pyPython
try:
    value = int("bad")
except ValueError:
    print("Conversion failed")
    raise

Har 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.

custom.pyPython
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.

chaining.pyPython
def parse_score(text):
    try:
        return int(text)
    except ValueError as error:
        raise ValueError("score must be a whole number") from error

from 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

assertion.pyPython
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.

eafp.pyPython
student = {"name": "Aman"}

try:
    print(student["score"])
except KeyError:
    print("Score not available")

Practical validation pattern

result.pyPython
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}")

Run validation example →

Common beginner mistakes

  • Bare except: laga kar every failure hide kar dena.
  • Huge try block 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.
  • finally me return use 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.
  • assert ko production input validation samajhna.

Beginner best practices

  • Only expected exceptions catch karo.
  • try block 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 finally ya 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/except se expected failure handle kar sakte ho?
  • Multiple specific exception handlers likh sakte ho?
  • else aur finally ka role samajh aaya?
  • raise se 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.

  1. Student name input lo.
  2. Three subject marks input lo.
  3. String marks ko float me convert karo.
  4. Conversion failure par ValueError handle karo.
  5. 0–100 range ke bahar mark ho to manually ValueError raise karo.
  6. Valid marks list me store karo.
  7. Average calculate karo.
  8. Empty valid-data case safely handle karo.
  9. Grade return karne ke liye function banao.
  10. At least one else block use karo.
  11. One finally block me completion message print karo.
  12. One custom InvalidMarksError version bhi try karo.
  13. Bare except: use mat karo.
  14. Deliberately invalid input dekar recovery test karo.

Open practice starter →