Python Error Handling
PythonErrors happen! Python uses try/except to handle them gracefully instead of crashing.
Key Points
try— code that might cause an errorexcept— what to do if error occursfinally— runs no matter what (cleanup code)raise— manually trigger an error- Common errors:
ValueError,TypeError,ZeroDivisionError,FileNotFoundError
Example — PYTHON
# Basic try/except
try:
num = int(input("Enter a number: "))
result = 100 / num
print(f"Result: {result}")
except ValueError:
print("Please enter a valid number! ❌")
except ZeroDivisionError:
print("Cannot divide by zero! ❌")
# Multiple exceptions
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError:
return "Invalid types"
finally:
print("Division attempted")
print(safe_divide(10, 2))
print(safe_divide(10, 0))
# File error handling
try:
with open("missing.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found! Creating it...")
with open("missing.txt", "w") as f:
f.write("New file created")
print("File created! ✅")
# Custom validation with raise
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
if age > 150:
raise ValueError("Age seems unrealistic!")
return age
try:
set_age(-5)
except ValueError as e:
print(f"Error: {e}") Result
Division attempted
5.0
Division attempted
Cannot divide by zero
File not found! Creating it...
File created! ✅
Error: Age cannot be negative!
5.0
Division attempted
Cannot divide by zero
File not found! Creating it...
File created! ✅
Error: Age cannot be negative!