Skip to content
Try and Except
step 1/7

Reading — step 1 of 7

Learn

~3 min readError Handling

Every program encounters errors. A user types "abc" where a number is expected. A file you need doesn't exist. A network request times out. A division by zero. You can't prevent all errors, but you can decide what happens when they occur. Python's exception handlingtry and except — gives you a way to attempt something risky and catch the error if it fails.

The basic shape

python

When an error occurs inside try:

  • Python looks for a matching except block.
  • If found, the except runs and the program continues.
  • If not found, the exception propagates up — eventually crashing the program if no one handles it.

If NO error occurs in try, all except blocks are skipped.

Catching multiple types in one block

python

A single except can catch any of multiple types — pass them as a tuple.

Capturing the exception object

python

as e binds the exception object to a name. You can read its message, print a traceback, or re-raise it.

else and finally

python
  • else runs only when no exception was raised in try. Useful for the "happy path."
  • finally always runs. Use it for cleanup (closing files, releasing locks).

Common exception types you'll see

  • ValueError — wrong value (int("abc"))
  • TypeError — wrong type ("a" + 1)
  • KeyError — missing dict key
  • IndexError — list/string index out of range
  • FileNotFoundError
  • ZeroDivisionError
  • AttributeErrorobj.missing_attr
  • RuntimeError — generic catch-all
  • Exception — base class of (almost) all the above

⚠️ Don't use bare except

python

Bare except catches EVERY exception including KeyboardInterrupt (Ctrl+C) and SystemExit. Worse, except: pass hides bugs — the program just silently does nothing wrong. Always catch the specific exception(s) you intend to handle:

python

EAFP — "Easier to Ask Forgiveness than Permission"

Python style prefers TRY-IT and handle errors over CHECK-FIRST:

python

Common mistakes

  • Catching too broadly: except: or except Exception hides bugs. Be specific.
  • Exception used for control flow when an if would work — exceptions are for exceptional cases.
  • Empty except body that silently swallows — at minimum, log the error.
  • Forgetting cleanup: if you open a file in try, ALWAYS close it (use with or finally).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…