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
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
| Error | Cause |
|---|---|
| ZeroDivisionError | Dividing by 0 |
| ValueError | int("abc") — wrong type of value |
| TypeError | "5" + 5 — mixing types |
| FileNotFoundError | Opening a missing file |
| IndexError | List index out of range |
Program 1: Safe Division
a = int(input("Numerator: "))
b = int(input("Denominator: "))
try:
print("Result:", a / b)
except ZeroDivisionError:
print("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
try:
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
except ValueError:
print("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
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")- Each
excepthandles a different error type. finallyalways runs — error or not — good for cleanup.
Raising Your Own Error
Use raise to signal an error yourself when input is invalid.
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)Common Mistakes
- Catching every error with a bare
except:— hides real bugs. - Putting too much code inside one
tryblock. - Forgetting that
finallyruns no matter what.
Practice Tasks
- Ask for two numbers and divide them safely.
- Keep asking for a number until the user enters a valid one.
- Open a file and handle FileNotFoundError nicely.
- Write a function that raises an error for a negative marks value.
Summary
- Exceptions are runtime errors; handling stops crashes.
tryruns risky code;exceptcatches specific errors.finallyalways runs;raisecreates your own error.
Exception क्या है?
Exception वह error है जो program चलते समय आती है (जैसे zero से भाग)। handle न करने पर program crash हो जाता है। Exception handling आपको error पकड़कर शालीनता से जवाब देने देता है।
try / except
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
a = int(input("Numerator: "))
b = int(input("Denominator: "))
try:
print("Result:", a / b)
except ZeroDivisionError:
print("Error: cannot divide by zero")try के बिना 0 से भाग program crash कर देता। अब यह friendly message print करता है।
Program 2: Safe Number Input
try:
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
except ValueError:
print("Please enter a valid number")User number की जगह text type करे तो int() ValueError देता है, जिसे हम पकड़ते हैं।
Program 3: कई except + finally
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")- हर
exceptअलग error type handle करता है। finallyहमेशा चलता है — error हो या न हो — cleanup के लिए अच्छा।
अपना Error Raise करना
Input गलत होने पर खुद error देने के लिए raise use करें।
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)सामान्य गलतियाँ
- 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 बनाता है।