New: Complete Beginner's Guide to Coding is now available in Premium
Updated: Indian Govt Exam roadmaps now include salary breakdowns & timelines
Tip: Use the Career Hub to explore all career paths in one place
Tutorials Python Python Error Handling

Python Error Handling

Python

Errors happen! Python uses try/except to handle them gracefully instead of crashing.

Key Points

  • try — code that might cause an error
  • except — what to do if error occurs
  • finally — 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!