A
AiTechWorlds
AiTechWorlds
try/except/else/finally, custom exceptions, context managers, exception chaining, and retry patterns in Python.
BaseException
βββ SystemExit
βββ KeyboardInterrupt
βββ GeneratorExit
βββ Exception
βββ ArithmeticError
β βββ ZeroDivisionError
β βββ OverflowError
βββ LookupError
β βββ IndexError
β βββ KeyError
βββ TypeError
βββ ValueError
βββ AttributeError
βββ NameError
βββ ImportError
β βββ ModuleNotFoundError
βββ OSError
β βββ FileNotFoundError
β βββ PermissionError
β βββ TimeoutError
βββ RuntimeError
βββ StopIterationtry:
result = 10 / int(input("Divisor: "))
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid number entered")
except (TypeError, OverflowError) as e:
print(f"Numeric error: {e}")
except Exception as e:
print(f"Unexpected error: {type(e).__name__}: {e}")
else:
print(f"Result: {result}") # runs only if NO exception occurred
finally:
print("Always runs β cleanup here")import logging
def process_file(path: str):
try:
with open(path) as f:
return f.read()
except FileNotFoundError as e:
logging.error(f"File missing: {path}")
raise # re-raise original exception, preserving traceback
except PermissionError as e:
raise RuntimeError(f"Cannot read {path}: permission denied") from e
# 'from e' chains exceptions β shows both in tracebackclass AppError(Exception):
"""Base class for all application errors."""
pass
class ValidationError(AppError):
def __init__(self, field: str, message: str):
self.field = field
self.message = message
super().__init__(f"Validation failed on '{field}': {message}")
class NotFoundError(AppError):
def __init__(self, resource: str, id: int):
super().__init__(f"{resource} with id={id} not found")
self.resource = resource
self.id = id
# Usage
try:
raise ValidationError("email", "must contain @")
except ValidationError as e:
print(e.field) # "email"
print(e) # "Validation failed on 'email': must contain @"# File β closed even if exception occurs
with open("data.txt", "r") as f:
content = f.read()
# Multiple context managers
with open("input.txt") as fin, open("output.txt", "w") as fout:
fout.write(fin.read().upper())
# Custom context manager using class
class TempDir:
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, exc_type, exc_val, exc_tb):
shutil.rmtree(self.path)
return False # False = do not suppress exceptions
# Custom context manager using contextlib
from contextlib import contextmanager
@contextmanager
def timer(label: str):
import time
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed:.3f}s")
with timer("sort"):
sorted(range(100_000), reverse=True)# Raise multiple exceptions at once
raise ExceptionGroup("multiple errors", [
ValueError("bad value"),
TypeError("wrong type"),
KeyError("missing key"),
])
# Handle specific types within the group
try:
raise ExceptionGroup("errors", [ValueError("x"), TypeError("y")])
except* ValueError as eg:
print(f"Value errors: {eg.exceptions}")
except* TypeError as eg:
print(f"Type errors: {eg.exceptions}")from contextlib import suppress
with suppress(FileNotFoundError):
os.remove("temp.txt") # silently ignored if file doesn't existimport time
def with_retry(func, retries=3, delay=1.0, exceptions=(Exception,)):
for attempt in range(retries):
try:
return func()
except exceptions as e:
if attempt == retries - 1:
raise
time.sleep(delay * (2 ** attempt)) # exponential backoffimport logging
import traceback
def safe_run(func, *args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
logging.error("Unhandled exception", exc_info=True)
# exc_info=True includes full traceback in log
return None| Exception | When Raised |
|---|---|
ValueError | Right type, wrong value (int("abc")) |
TypeError | Wrong type for operation ("a" + 1) |
KeyError | Dict key doesn't exist |
IndexError | List index out of range |
AttributeError | Object has no such attribute |
NameError | Variable not defined |
FileNotFoundError | File/directory does not exist |
PermissionError | OS denies access |
TimeoutError | Operation timed out |
StopIteration | Iterator is exhausted |
RecursionError | Max recursion depth exceeded |
MemoryError | Out of memory |
AssertionError | assert statement failed |
except: β catches SystemExit and KeyboardInterrupt, preventing clean shutdownexcept: pass) β hides bugs that will surface later elsewheretry/except for logic is slow; use if/else for expected conditionsraise ... from when chaining β loses the original exception contextfinally for resource cleanup β use context managers (with) instead, they handle it automaticallyAdvertisement
Get more notes like this daily on Telegram!
Free study notes, cheat sheets & AI tips
Last reviewed on June 13, 2026 by the AiTechWorlds Notes Team. Free cheat sheet β no signup required.
Advertisement
Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content β 100% free!
No spam. Leave anytime.