Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

How can I catch only the exceptions my function can handle?

Quick answer

Catch an exception only when your function can respond to that specific failure in a defined, useful way. Replace a broad except Exception with the expected exception type, such as ValueError when converting user input. Python lets unmatched exceptions continue to an outer handler or remain unhandled, so unexpected failures stay visible instead of being mistaken for normal results. [S1]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

I have a function that converts a value to an integer. Is except Exception a reasonable way to stop it from crashing?

Geez

Usually not. A broad handler can make unrelated failures look like ordinary bad input. Instead, identify the failure the function is actually prepared to handle. For integer conversion, the intended recovery might be to return a fallback when the input cannot be converted; that is a ValueError case. Python checks an exception against the types named in except; an unmatched exception continues to an outer handler or remains unhandled. [S1]

Before:

def parse_count(text):
    try:
        return int(text)
    except Exception:
        return 0

This treats every caught failure as “invalid count,” even if the problem is unrelated to the input. The 0 fallback is an example choice, not a universally appropriate default.

Follow-up question

What would the narrower version look like, and what should happen to other errors?

Geez

Name the exception that corresponds to the condition you can handle, and make the recovery clear. For example, if this function’s agreed behavior is to use zero when the text is not an integer:

After:

def parse_count(text):
    try:
        return int(text)
    except ValueError:
        return 0

Now the fallback applies to the conversion failure the function expects. Other exception types are not handled by this clause; they can reach a caller or remain unhandled. The Python tutorial recommends being as specific as possible and allowing unexpected exceptions to propagate, rather than using Exception as a catch-all. [S1] The example does not establish that zero is the right fallback for your application: choose a result your callers can interpret safely.

Follow-up question

How do I decide whether to catch one type or several, and where should the handler go?

Geez

Put the handler at the level that knows what useful response to take. Ask what condition occurred, what recovery this function can perform, and whether its callers can make a better decision. If two exception types genuinely call for the same response, Python allows them in one clause; if they need different responses, use separate clauses. [S1]

For instance, a function might handle ValueError by returning a documented input fallback, but let another failure propagate because it has no sensible recovery for it. Do not add exception types merely because they might occur. If you cannot explain the recovery for a type, that is a strong reason not to catch it here.

Follow-up question

Can you give me a short review checklist I can apply to my handler?

Geez

Use this checklist:

  1. Name the specific operation that may fail, such as converting input.
  2. Identify the exception type for the failure you intend to handle.
  3. State the recovery in plain language: fallback, helpful error, or another defined response.
  4. Catch only types for which that recovery makes sense; use separate clauses when responses differ.
  5. Leave unexpected exceptions uncaught here, unless this function has a deliberate, useful way to handle them.
  6. Check that callers can distinguish the fallback from a valid result when that distinction matters.

A handler should document a real boundary of responsibility, not just make an error disappear. Python’s exception matching and propagation behavior supports that approach, but the cited tutorial does not determine which fallback or error policy your particular program should choose. [S1]

A practical checklist

  • Identify the operation that can fail.

  • Choose the exception type for the specific failure you intend to handle.

  • Write down the useful recovery for that exception.

  • Use separate clauses when different exception types need different responses.

  • Let failures you cannot handle propagate to a suitable caller.

  • Make sure a fallback cannot be confused with a valid result.

A few more useful answers

Should I catch `Exception`?

The Python tutorial recommends catching as specifically as possible and allowing unexpected exceptions to propagate, rather than using Exception as a catch-all. [S1]

Can one `except` clause handle more than one exception type?

Yes. Python allows several types in one clause. Use that when the same recovery makes sense for each; use separate clauses when the responses should differ. [S1]

Should I return a fallback value after catching an exception?

Only if that fallback is part of the function’s intended behavior and callers can interpret it correctly. The example’s zero is illustrative, not a recommendation for every application.

Sources

References used for this guide.

  1. [S1] Errors and Exceptions — Python 3.11 Tutorial
    docs.python.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work