Python Exception Handling

Introduction

Exceptions happen when something goes wrong during code execution — missing files, invalid input, division by zero, network issues, etc. Python provides try, except, else, and finally to handle errors safely and avoid crashes.

1. Basic try/except

try:
    x = 10 / 0
except:
    print("An error occurred")
    

2. Catching Specific Exceptions

try:
    number = int("abc")
except ValueError:
    print("Invalid number")
    

3. Multiple Except Blocks

try:
    f = open("file.txt")
except FileNotFoundError:
    print("File missing")
except PermissionError:
    print("No permission")
    

4. else Block

Runs when no exceptions occur.

try:
    print("Everything OK")
except:
    print("Error")
else:
    print("No errors detected")
    

5. finally Block

Runs ALWAYS — useful for cleanup.

try:
    f = open("data.txt")
finally:
    print("Closing file")
    

6. Raising Exceptions

def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")

check_age(-5)
    

7. Custom Exceptions

class BalanceError(Exception):
    pass
    
raise BalanceError("Insufficient balance")
    

8. Try/Except in Loops

data = ["10", "5", "abc", "2"]

for item in data:
    try:
        print(int(item))
    except ValueError:
        print("Skipping invalid entry:", item)
    

9. Logging Exceptions

import logging

try:
    x = 1 / 0
except Exception as e:
    logging.error("Error happened: %s", e)
    

10. Getting Full Traceback

import traceback

try:
    open("missing.txt")
except Exception:
    traceback.print_exc()
    

11. Silent Failures (use carefully)

try:
    risky_operation()
except:
    pass  # ignore
    

12. Best Practices

Summary