⚡ What is Error Handling?
Error handling means predicting, catching, and responding to errors so your program doesn’t crash.
Real-life analogy:
Imagine you’re ordering food online. If the restaurant is closed, the app doesn’t crash — it shows “Restaurant unavailable”.
That’s error handling.
⚡ Types of Errors in Python
1️⃣ Syntax Errors
- Mistakes in code structure.
- Program won't run until fixed.
Example:
print("hello"
Missing ) → syntax error.
2️⃣ Runtime Errors (Exceptions)
- Code is syntactically correct but fails during execution.
Example:
10 / 0 # ZeroDivisionError
Real-life example:
Trying to withdraw ₹2000 when your wallet has ₹500.
3️⃣ Logical Errors
- No crash, but wrong output due to incorrect logic.
Example:
# Intended: average of two numbers
avg = (a + b) / 2 # correct
avg = a + b / 2 # wrong → no error but wrong logic
Real-life example:
Setting an alarm for 6 PM instead of 6 AM — phone doesn’t complain, but logic is wrong.
⚡ The try / except Block
Basic structure:
try:
# code that might fail
except:
# what to do if it fails
⚡ Catching Specific Exceptions (best practice)
Why specific?
It’s like telling the delivery app what to do for each issue:
- Restaurant closed
- Payment failed
- Wrong address
Example:
try:
num = int(input("Enter number: "))
result = 10 / num
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("Number cannot be zero.")
⚡ else Block (runs when no error occurs)
Real-life analogy:
If payment is successful, THEN show “Order confirmed”.
try:
f = open("data.txt")
except FileNotFoundError:
print("File missing!")
else:
print("File opened successfully!")
f.close()
⚡ finally Block (ALWAYS runs)
Real-life analogy:
After cooking, you always turn off the gas — whether food is burnt, undercooked, or perfect.
try:
f = open("data.txt")
content = f.read()
except FileNotFoundError:
print("File not found")
finally:
print("Cleaning up...")
⚡ Raising Your Own Errors (raise)
You can trigger errors when invalid data is detected.
Real-life example:
If someone tries to book 12 tickets (but limit is 10), you show an error.
def book_tickets(n):
if n > 10:
raise ValueError("Cannot book more than 10 tickets")
return "Tickets booked!"
book_tickets(12)
⚡ Custom Exceptions
Useful in large applications (AI pipelines, payment apps, etc):
Real-life example:
You create a custom error: LowBatteryError.
class LowBatteryError(Exception):
pass
def start_camera(battery):
if battery < 10:
raise LowBatteryError("Battery too low!")
print("Camera started.")
start_camera(5)
⚡ Real-Life Relatable Examples
✔ Example 1: ATM Machine
ATM checks:
- Card validity →
ValueError - Wrong pin →
AuthenticationError(custom) - Low balance →
InsufficientFundsError
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Balance too low.")
return balance - amount
try:
new_balance = withdraw(500, 1000)
except InsufficientFundsError as e:
print(e)
✔ Example 2: AI Model Loading (ML Example)
try:
model = load_model("model.pkl")
except FileNotFoundError:
print("Model missing! Download it again.")
✔ Example 3: Reading JSON Config
import json
try:
data = json.loads('{"name": "Ali"') # missing ending }
except json.JSONDecodeError:
print("Invalid config file format!")
⚡ Quick Summary (for memory)
- try → attempt
- except → recovery
- else → success block
- finally → cleanup
- raise → throw custom error
- Custom Exceptions → your own meaningful error types
Top comments (0)