Exception Handling Rules

Core Principle

Python uses exceptions for error handling, not return codes. Let exceptions propagate naturally unless you have a specific recovery strategy.

General Rules

1. Catch specific exceptions only — avoid bare except Exception:. Catching all exceptions hides bugs and unexpected errors. Specify the exceptions you expect and can handle. Never catch exceptions just to return None or False.

2. Let exceptions propagate if you can't recover — Don't wrap exceptions without adding value. Don't convert exceptions to return codes or sentinel values. The caller is better positioned to decide how to handle errors.

3. Catch exceptions only for recovery — Provide a meaningful fallback or default value. Try multiple fallback strategies (e.g., alternative libraries). Clean up resources (though context managers are preferred). Re-raise fatal errors immediately (FileNotFoundError, PermissionError).

4. Python's default traceback is your friend — More informative than custom error messages. Shows the full context of what went wrong. Don't suppress it unless you have good reason.

Application-Specific Guidelines

Fail-Fast Scripts (one-shot tools, batch processing)

Let all errors propagate to stop execution immediately. Don't catch file reading or parsing errors. Invalid input makes the entire operation meaningless. Prevents wasted resources (API calls, processing time, costs).

Long-Running Programs (servers, daemons, email processors)

Use except Exception: only at top-level task/request loops. MUST log full stack trace using logging.exception() or traceback.print_exc(). Each iteration should be independent enough to skip on failure. Program must continue serving other requests after logging the error. Ensures one bad request/task doesn't crash the entire service.

version1