🟢 Beginner  ·  Lesson 18

Exception Handling

Exception Handling

What is an Exception?

An exception is an error that happens while a program runs (like dividing by zero). Without handling, the program crashes. Exception handling lets you catch the error and respond gracefully.

try / except

Python – tryexcept
try:
    # risky code
    risky_operation()
except SomeError:
    # runs if that error happens
    handle_it()

Python tries the try block. If an error occurs, it jumps to the matching except instead of crashing.

Common Errors

ErrorCause
ZeroDivisionErrorDividing by 0
ValueErrorint("abc") — wrong type of value
TypeError"5" + 5 — mixing types
FileNotFoundErrorOpening a missing file
IndexErrorList 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

Without the try, dividing by 0 would crash the program. Now it prints a friendly message.

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

If the user types text instead of a number, int() raises ValueError, which we catch.

Program 3: Multiple 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
  • Each except handles a different error type.
  • finally always runs — error or not — good for cleanup.

Raising Your Own Error

Use raise to signal an error yourself when input is invalid.

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

Common Mistakes

  • Catching every error with a bare except: — hides real bugs.
  • Putting too much code inside one try block.
  • Forgetting that finally runs no matter what.

Practice Tasks

  1. Ask for two numbers and divide them safely.
  2. Keep asking for a number until the user enters a valid one.
  3. Open a file and handle FileNotFoundError nicely.
  4. Write a function that raises an error for a negative marks value.

Summary

  • Exceptions are runtime errors; handling stops crashes.
  • try runs risky code; except catches specific errors.
  • finally always runs; raise creates your own error.

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कारण
ZeroDivisionError0 से भाग
ValueErrorint("abc") — गलत type की value
TypeError"5" + 5 — types मिलाना
FileNotFoundErrorन मौजूद file खोलना
IndexErrorList 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 छुपा देता है।
  • एक try block में बहुत ज़्यादा code डालना।
  • यह भूलना कि finally हर हाल में चलता है।

Practice Tasks

  1. दो numbers पूछकर safely divide करें।
  2. तब तक number पूछते रहें जब तक user valid न दे।
  3. File खोलकर FileNotFoundError अच्छे से handle करें।
  4. एक function लिखें जो negative marks पर error raise करे।

सारांश

  • Exceptions runtime errors हैं; handling crashes रोकता है।
  • try risky code चलाता है; except specific errors पकड़ता है।
  • finally हमेशा चलता है; raise अपना error बनाता है।
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

WhatsApp