raise — Intermediate Examples
Throws an exception manually
Re-raising and chaining exceptions
Using raise in except blocks.
python
# Re-raise the current exception def process(data): try: return int(data) except ValueError: print(f"Warning: could not process {data!r}") raise # re-raise the same exception try: process("abc") except ValueError as e: print(f"Caught re-raised: {e}") # Exception chaining with 'from' class AppError(Exception): pass def load_config(path): try: raise FileNotFoundError(f"No such file: {path}") except FileNotFoundError as e: raise AppError("Configuration failed") from e try: load_config("config.yaml") except AppError as e: print(f"Error: {e}") print(f"Caused by: {e.__cause__}")
Bare 'raise' re-throws the current exception. 'raise X from Y' chains exceptions, setting __cause__ for traceback clarity.
Custom exception hierarchies
Defining your own exception classes.
python
class APIError(Exception): def __init__(self, message, status_code=500): super().__init__(message) self.status_code = status_code class NotFoundError(APIError): def __init__(self, resource): super().__init__(f"{resource} not found", 404) class AuthError(APIError): def __init__(self): super().__init__("Authentication required", 401) errors = [NotFoundError("User"), AuthError(), APIError("Server crash")] for err in errors: print(f"[{err.status_code}] {err}")
Expected Output
[404] User not found [401] Authentication required [500] Server crash
Custom exception hierarchies let you catch broad categories (APIError) or specific ones (NotFoundError). Store extra data as attributes.
Want to try these examples interactively?
Open Intermediate Playground