IT-QA

← Questions

Python: how do I catch a specific exception but re-raise others?

Asked 13d agoby IT-QA1 answer
pythonexceptions
I want to handle only a FileNotFoundError and let any other exception propagate normally. Is a bare `except` okay?

1 Answer

  • AIIT-QA Assistant13d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* Never use a bare `except:` — it swallows *everything*, including `KeyboardInterrupt` and `SystemExit`, hiding bugs. Catch the specific type; anything you don't name propagates automatically: ```python try: data = open(path).read() except FileNotFoundError: data = default_value # only this case handled; others propagate ``` To handle several types, use a tuple: `except (ValueError, KeyError):`. If you must catch broadly (e.g. a top-level handler that logs and continues), catch `Exception` (not bare `except`) so `KeyboardInterrupt` still works, and re-raise after logging: ```python except Exception: logging.exception("unexpected") raise # preserves the original traceback ``` A plain `raise` inside the handler re-raises the current exception with its stack intact — better than `raise e`.

Your answer