Skip to the page

Functions and flow · core

try, except, else, finally and reviewing error handling

The first matching except runs, else runs only when nothing was raised, and finally always runs. Swallowing errors with except Exception: pass hides bugs and loses data, and a reviewer must be able to spot it.

The notes

What you must know

  • The first matching except runs, so put specific exceptions before general ones.
  • else runs only when nothing was raised, which keeps the try block small. finally always runs.
  • A return inside finally overrides an earlier return and swallows any exception. Python 3.14 warns about it (PEP 765).
  • except Exception: pass hides bugs and data loss. A bare except: also catches KeyboardInterrupt and SystemExit.
  • raise ... from e sets cause so the log shows both errors. e.add_note() (3.11) adds context.
  • ExceptionGroup and except* (3.11) come from asyncio.TaskGroup and code that runs many tasks.
  • Code review of a cleaning function: a shared default list, a bare except, de-duplicating before lower-casing, a list used for membership (use a set), string += in a loop (collect, then join), open() without with or encoding, changing the caller's dicts, type(x) == str instead of isinstance, and no record of rejected rows.
  • Better design: catch KeyError and ValueError per row, log the row number, return clean records plus a count of rejects, and add tests for duplicates in different case, a bad age, a missing field and two files in a row.

The red pen

Common traps: mistake → fix

  • Mistake: Catch Exception at every level to be safe

    Fix: catch narrow exceptions and handle them once at the right boundary.

  • Mistake: Log and re-raise at every layer

    Fix: the same error appears many times; log once where it is handled.

  • Mistake: A bare except is the same as except Exception

    Fix: it also catches KeyboardInterrupt and SystemExit.

Easy to hard

Questions interviewers ask, easy to hard

  1. When do try, except, else and finally each run?
  2. What is wrong with except Exception: pass?
  3. What does raise ... from e do?
  4. Review this data-cleaning function as a pull request. What do you ask to change?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview