try and except

Catching the errors you expect, letting through the ones you do not, and why a bare except is worse than no except at all.

Overview

Catching the errors you expect, letting through the ones you do not, and why a bare except is worse than no except at all.

In this guide
  1. The shape
  2. Catch what you expect, nothing more
  3. as e, and why you want it
  4. else and finally
  5. Raising your own
  6. Ask forgiveness, not permission
  7. Which exceptions to expect
  8. Keep the try block small
  9. Failing loudly is usually right
  10. Cleanup belongs to with
  11. A retry loop, whole
  12. The hierarchy, and what catching one gets you
  13. Raising with the cause attached
  14. Exceptions of your own
  15. The middle ground between crashing and swallowing
  16. Questions people ask about try and except
  17. try and except: recap in one screen

try_except.py

try_except.py Python 3
Output

                    

bare_except.py

bare_except.py Python 3
Output

                    

Worth knowing

Catch the specific exception you expect: except ValueError:, not except:.
A bare except also swallows your typos, turning a crash into wrong output.
else runs when nothing raised. finally runs either way.
as e gives you the exception object, which carries the detail worth logging.

try and except: A Practical Guide

A try block runs code that might fail. An except block says what to do when a exact failure happens. The trouble isn't the syntax. It's being disciplined about which failures you really catch.

The shape

try:
    return int(text)
except ValueError:
    return None

If int() raises ValueError, control jumps to the handler. If it raises something else, the handler is skipped and the error keeps traveling up the call stack. That selectivity is the point.

Every program eventually encounters input it did not expect. A user types letters where a number belongs. A file turns out to be missing. A network request times out. Without error handling, any of these stops the program with a traceback. Sometimes that is acceptable during development, but a program handed to another person needs to respond to problems rather than crash.

Python uses exceptions for this. An exception is an object that describes what went wrong. When something raises an exception, Python stops executing the current block and looks for a try/except that matches. If it finds one, control jumps to the handler. If it does not find one in the current function, it jumps up to the caller, and then the caller's caller, until it either finds a handler or reaches the top level and prints a traceback.

The most common mistake beginners make is catching too broadly. Writing except: or except Exception: catches every error, including ones you did not anticipate. That hides bugs. A misspelled variable name raises NameError, which is a programming mistake, not a runtime problem. If your handler swallows it, you never find out.

The right practice is to catch the specific exception you expect. If you are converting a string to a number, catch ValueError. If you are opening a file, catch FileNotFoundError. Name the exception type after except so that genuine bugs still surface as tracebacks you can investigate.

This page covers the try/except shape, catching specific exceptions, the else clause for code that should run only when no exception occurred, finally for cleanup that must happen regardless, and the common traps around broad catches.

Catch what you expect, nothing more

except:    # catches all

This is almost always a mistake. It catches the error you were thinking of. Also your typos, your NameErrors, your AttributeErrors from a refactor you half-finished. The program stops crashing and starts making wrong answers quietly. This Is strictly worse: a crash tells you where to look.

The second program on this page has a deliberate typo inside a bare except. It returns 0, cheerfully. Nothing anywhere says a name was misspelled.

Name the exception:

except ValueError:
except (KeyError, IndexError):
except Exception as e:  # broad. But At least not BaseException

as e, and why you want it

except ValueError as e:
    print("could not convert:", e)

The exception object carries the detail. Which key was missing. This Value wouldn't parse. Discarding it and printing "a thing went wrong" throws away the only part that would have helped.

else and finally

  • else runs when the try block raised nothing. It keeps the risky line alone in the try. The handler can't accidentally catch an error from the follow-up code.
  • finally runs either way, raised or not. It's where cleanup goes.

For files and locks, prefer with. This Does the same job with less ceremony.

Raising your own

Handling is half of it. When a caller hands you a thing hopeless, say so:

if age < 0:
    raise ValueError(f"age cannot be negative, got {age}")

Include the offending value in the message. "Invalid input" costs the next person a debugging session. "got -1" ends it right away.

Ask forgiveness, not permission

Python leans toward trying the op and handling the failure, rather than checking first. Checking if key in d before d[key] does the lookup twice and still has a gap between the check and the use. Try it and catch KeyError. It's faster in the common case and correct in all of them.

Which exceptions to expect

The instruction to catch exact exceptions is easy to agree with and harder to follow, because it needs knowing what a piece of code can raise. Three ways to find out, in order of trust.

Read the docs: the standard library is clear about what its functions raise, and int(), open() and dict lookups all doc theirs. Run it and see: trigger the failure on purpose once, read the traceback, and catch what really appeared. And reason about it: an op that parses can raise ValueError, one that touches the filesystem can raise OSError, one that indexes can raise IndexError or KeyError.

Catching Exception is the honest middle ground when you truly can't enumerate them - a plugin boundary, a top-level handler that must not crash the program - and it's different from a bare except, because it still lets KeyboardInterrupt and SystemExit through. Those two are how a user stops your program, and swallowing them is how a program turns hopeless to quit.

Keep the try block small

A try that wraps twenty lines catches errors from all twenty, including ones you never thought about. If the handler says "couldn't parse the date", but the block also holds a DB call, then a DB failure now reports itself as a date problem, and the person debugging it starts in the wrong place.

Wrap the line that can fail, and put the follow-up work in else. The block stays honest about what it's handling.

Failing loudly is usually right

There's a reflex, above all early on, to wrap any of it that has ever raised in a try and carry on. It feels defensive. What it really does is convert a loud, located failure into a quiet, wrong result that surfaces a place else with no traceback pointing home.

An exception isn't automatically a problem to suppress. It's info, and often the most handy info the program will give. Handle the ones you have a real answer for - a missing optional file, a user typing letters into a number field, a network call worth retrying - and let the rest travel. A crash in development is a bug report that writes itself.

Cleanup belongs to with

finally ensures that cleanup runs, and for files, locks and links there's a better tool: a context manager. with open(...) closes the file whether the block succeeded or raised, without the extra indentation and without the risk of losing. Reach for finally when there's no context manager for what you're doing, and for with when there's.

A retry loop, whole

The most common real use of try outside parsing, with the loop else doing the "we ran out of attempts" branch:

attempts = []

def flaky():
    attempts.append(1)
    if len(attempts) < 3:
        raise ConnectionError("timed out")
    return "ok"


for attempt in range(1, 5):
    try:
        print("result:", flaky())
        break
    except ConnectionError as e:
        print(f"attempt {attempt} failed: {e}")
else:
    print("gave up")
attempt 1 failed: timed out
attempt 2 failed: timed out
result: ok

Four details are worth copying. The try holds only the call that can fail, so a bug in the printing wouldn't be caught as a link problem. The except names one exact exception. So A TypeError from a refactor still crashes loudly. The as e keeps the message. This Is the part that tells you *why* it failed. And the break on success means the else runs only when each attempt was used. This Is just the "gave up" case.

In production this would sleep between attempts, with the delay growing each time, and would only retry errors that are really transient — a timeout, yes. A PermissionError, never, because retrying it will fail the same way four more times and delay the real error.

The hierarchy, and what catching one gets you

Exceptions form a tree, and catching a class catches each subclass beneath it. That is what makes except Exception catch almost all, and it's also how you catch a handy family without listing its members.

At the top is BaseException. right beneath it sit SystemExit, KeyboardInterrupt and GeneratorExit — the three that are *not* errors, but control flow. Exception holds all else, and is what you should catch when you must catch broadly, because it leaves those three alone. This is the concrete difference between except Exception: and a bare except:, and it's the reason the bare form makes a program hopeless to interrupt with Ctrl-C.

Below Exception, the groupings are handy. OSError covers FileNotFoundError, PermissionError, IsADirectoryError, TimeoutError and the rest of the filesystem and network family. So except OSError is a reasonable way to say "any of it the operating system refused". ArithmeticError covers ZeroDivisionError and OverflowError. LookupError covers KeyError and IndexError, which is at times just what you want when reaching into a structure that might be short or missing a field.

Knowing the tree turns "catch exact exceptions" from a rule into a thing actionable: catch the narrowest class that covers the failures you really have an answer for.

Raising with the cause attached

When you catch an exception and raise a different one, the first is worth keeping:

try:
    try:
        int("abc")
    except ValueError as exc:
        raise RuntimeError("could not read config") from exc
except RuntimeError as e:
    print(type(e).__name__ + ":", e)
    print("caused by:", type(e.__cause__).__name__)
RuntimeError: could not read config
caused by: ValueError

from exc sets __cause__, and the printed traceback then shows both: the low-level failure, the line "The above exception was the direct cause of these exception", and your higher-level message. You get the *what* and the *why* in one traceback.

Without from, Python still attaches the first as __context__ and prints "During handling of the above exception, another exception occurred" — which is nearly as handy and reads as accidental rather than deliberate. raise ... from None suppresses it fully. This Is at times right when the inner error is noise a caller can't act on.

The reason this matters is that translating exceptions is good practice. A library that lets a raw KeyError from its inner dict escape has leaked its setup. One that raises ConfigError("missing 'host'") from exc has given the caller a thing to catch and the maintainer a thing to debug.

Exceptions of your own

Defining one is a single line, and the payoff is that callers can catch just your failure:

class ConfigError(Exception):
    pass

Subclass Exception, not BaseException. Name it for the problem rather than the place, and end it with Error by rule.

The reason to bother is selectivity. A caller who wants to handle a configuration problem and let all else through can't do that if you raised ValueError, because ValueError is also what int() raises three frames down. A dedicated class makes the handler precise.

A small hierarchy pays off in a library: one base class such as ThingError(Exception), with exact subclasses beneath it. Callers who want all catch the base. Callers who care about one case catch the subclass; and adding a new failure mode later doesn't break either.

Attach the data rather than only formatting it into the message. An exception that stores self.path or self.field lets a handler make a choice, where a handler given only a string has to parse English to find out what went wrong.

The middle ground between crashing and swallowing

The advice to let exceptions travel and the need for a program that keeps running are both real, and the space between them is where logging lives.

A handler has three honest choices. Handle it. You know what the failure means and what to do instead. Translate it. Catch it, raise a thing more real with from, and let it continue upward. Or record it and re-raise, which is what logging.exception is for: it writes the message and the full traceback to wherever logs go, and a bare raise afterwards sends the exception on its way.

try:
    process(record)
except ValueError:
    logging.exception("skipping record %r", record.id)
    continue

That pattern — log with the traceback, then skip this item and carry on — is the correct shape for batch work. Here One bad record shouldn't end a run over ten thousand. The critical part is logging.exception rather than logging.error, because the first includes the traceback and the second throws it away.

What isn't an honest choice is except Exception: pass. It's the one form that destroys info without replacing it, and the resulting program does not fail — it makes output that is quietly incomplete, which is the hardest kind of wrong to notice.

Questions people ask about try and except

What is the difference between except: and except Exception:? The bare form also catches KeyboardInterrupt and SystemExit, so it stops Ctrl-C from working. Never use it.

Can I catch a few exceptions in one handler? Yes, with a tuple: except (KeyError, IndexError) as e:.

Does finally run if the try returns? Yes. It runs on each exit path, including return and break.

What happens if finally itself raises? Its exception replaces what was in flight. This Is why finally blocks should be simple.

How do I re-raise after logging? A bare raise inside the handler re-raises the current exception with its first traceback intact.

Should I use exceptions for control flow? Python does, more than most languages — StopIteration ends each for loop. Use them for the exceptional path, not as a substitute for an if.

Is try/except slow? Setting up a try is nearly free. Raising and catching isn't. That is why "ask forgiveness" wins when failures are rare and loses when they're the common case.

What is an exception group? From Python 3.11, ExceptionGroup carries a few exceptions at once — raised by concurrent code where more than one task failed — and except* handles them selectively.

try and except: recap in one screen

  • Catch the narrowest exception you've an answer for. A bare except: also swallows Ctrl-C.
  • Keep the try block down to the line that can fail, and put the follow-up in else.
  • as e keeps the detail. This Is the part that makes the message handy.
  • raise NewError(...) from exc preserves the cause, so the traceback shows both the what and the why.
  • An exception you can't handle is info, not a problem — letting it travel beats a quiet wrong answer.

Check yourself

0 of 3

Answer without scrolling back up.

  1. Why is a bare `except:` discouraged?

  2. When does an `else` block on a try run?

  3. What does `as e` give you?

Cheat sheet

try and except

Catch specific exceptions with try/except, handle them without crashing, and see why bare except clauses hide the bugs you need to find.

PYTHON · vizlearn.in/python/try_and_except.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.