Python Tutorial - Error Handling
๐ก๏ธ Error Handling - Errors Ko Sambhalo
๐ Real Life Mein:
Problems handle karna:
๐ฑ "Network lost - Retry button dikhao"
๐ณ "Wrong PIN - 3 attempts allowed"
๐ "File not found - Create new file"
๐ "Invalid input - Ask again"
Program crash na ho - Error handle karo!
โ Without Error Handling
Program Crashes!
# User ne text diya number ki jagah
age = int(input("Age: ")) # "abc" โ CRASH! ๐ฅ
print(age)
โ With Error Handling
Try-Except Block
try:
age = int(input("Age: "))
print(f"Age: {age}")
except:
print("Please enter a valid number!")
# Program continues...
๐ฏ Practical Example - Safe Calculator
Division with Error Handling
try:
num1 = int(input("Number 1: "))
num2 = int(input("Number 2: "))
result = num1 / num2
print(f"Result: {result}")
except ValueError:
print("โ Please enter numbers only!")
except ZeroDivisionError:
print("โ Cannot divide by zero!")
except Exception as e:
print(f"โ Some error: {e}")
finally:
print("โ
Calculation attempt completed!")
๐ง Try-Except Structure:
try:- Code jo error de sakta haiexcept:- Error aaye toh kya karofinally:- Har haal mein run (optional)
Best Practice: Specific errors catch karo (ValueError, ZeroDivisionError) generic Exception se better hai!
Example
try:
x = 10 / 0
except:
print("Error!")