Great question! Whether to log and exit or let the exception propagate depends largely on the context of your application.
Here's a breakdown of when each approach makes sense:
💡 Use try/except with logger.critical(...); sys.exit(1) when:
✅ You're at the entry point (e.g., if __name__ == '__main__':)
- This pattern belongs at the top level of your application, like a CLI script or the main control flow, where:
- You don’t have any higher-level code to report to.
- You want to log an unrecoverable error and then cleanly exit the program.
- Example:
def main():
try:
run_application()
except Exception as e:
logger.critical(f"Application failed with error: {e}", exc_info=True)
sys.exit(1)
if __name__ == '__main__':
main()
✅ You're at a boundary where graceful shutdown is critical
- Some background processing frameworks, cron jobs, or services need predictable exit codes and logging.
❌ Avoid logging and exiting deep inside code/modules. Let exceptions propagate when:
🔁 You're inside a library/module:
- Don’t assume control over whether to exit.
- Let the caller handle the exception (they might want to retry, ignore, or wrap it).
❓ You're unsure how the exception should be handled:
- You may not know if the error is recoverable or not – it’s not your code’s job at that level to decide.
Instead:
def some_function():
try:
...
except SomeError as e:
logger.error("Something went wrong.", exc_info=True)
raise # Propagate the exception upward
✔️ Best Practice Summary
| Context | Handle + Log + Exit | Let It Propagate (Maybe log) |
|---|
Entry point (main) | ✅ Yes | Optional |
| Deep in call stack/module | ❌ Avoid | ✅ Yes |
| Reusable library | ❌ Avoid sys.exit() | ✅ Yes |
| CLI application | ✅ Reasonable | May also be valid |
Bonus: For Libraries – Avoid sys.exit()
If you're building code you'll reuse, sys.exit() is actively harmful:
- It kills the entire process.
- It can’t be caught.
- It makes the library non-reusable in a larger system.
TL;DR:
- Use the
try/except + logger.critical(...) + sys.exit(1) only at the top level (e.g., main()) when terminating makes sense.
- In all other cases, just log and
raise, or let the exception bubble up unhandled.
- Never call
sys.exit() in libraries or reusable code.
Let me know if you'd like a ready-made main script template with this pattern!