🚨 Error Handling

Exceptions & Error Management

Exception Handling

Exceptions are errors that occur during program execution. Python provides try/except blocks to catch and handle errors gracefully.

💻 Try/Except Basics

# Basic exception handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

# Multiple exceptions
try:
    num = int(input("Enter number: "))
    result = 10 / num
except ValueError:
    print("Invalid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

# Catch all exceptions
try:
    risky_operation()
except Exception as e:
    print(f"Error occurred: {e}")

🔧 Finally & Else

try:
    file = open('data.txt', 'r')
    data = file.read()
except FileNotFoundError:
    print("File not found!")
else:
    # Runs if no exception
    print("File read successfully!")
finally:
    # Always runs (cleanup)
    if 'file' in locals():
        file.close()

# Raising exceptions
def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    return age

# Custom exceptions
class InvalidEmailError(Exception):
    pass

def validate_email(email):
    if '@' not in email:
        raise InvalidEmailError("Invalid email format")

🎯 Key Takeaways