Concepts / Writing Functions That Handle Errors

Writing Functions That Handle Errors

try-except is an insurance policy on a sequence of statements, allowing you to respond to errors instead of crashing.

  • Programming

When the Risky Step Fails

A function may contain an operation that can produce an error. If that possibility is expected, the function can place the relevant sequence of statements in a try block and provide an except block for the error path. This gives the function a planned response instead of allowing the error to make the program crash.

What do you think happens?

A function reaches a try block, and every statement inside it succeeds. Which path should you predict?

  • Python jumps to the except block

  • Python skips the except block

  • Python repeats the try block automatically

Reveal answer
Answer:

Python skips the except block.

Python executes the try block first. When no exception occurs, the except block is skipped.

Two Possible Execution Paths

try blockexecute statementslater statementsexcept skippedexcept blockhandle exceptionchosen responsefix, retry, or endgracefullyno exceptionexception occurshandler responds
What happens next when the statements in the try block succeed, and what changes when one of them raises an exception?

The try block is the first path Python examines. When all of its statements run successfully, Python skips the except block and proceeds with the function's later behavior. When a statement in the try block raises an exception, Python changes control flow and jumps to the except block. The handler then gives the function control over the response.

trybegin protected sequencerisky operationmay raise exceptionexceptbegin responsehandler responserespond to errorlater statementsafter try-exceptprotectsif exceptionif successfulruns
How are the protected statements, the exception handler, and the statements after the block connected?

A Focused Handler

A good try block is focused. Put the operation that might fail inside it, rather than wrapping an unrelated large section of the function. The source specifically identifies invalid user input and missing files as expected errors for try-except handling. Keeping the protected sequence focused makes it clearer which operation needs a response.

python

This example illustrates the structure rather than a complete input implementation. The potentially failing input operation is inside the try block. If it raises an exception, control moves to the except block, which supplies a fallback response. If it succeeds, the except block is skipped and the function continues with its later return.

risky operationexception occursexcept handlercontrol returns to functionfix problemtry againend gracefullyraises exceptionone choiceanother choiceanother choice
After an exception reaches the handler, does the function fix the problem, try again, or end gracefully?

Tracing a Missing File

Worked example

Predicting the path

A function tries to open a file that is missing. The file operation is inside a try block, and the except block provides a message that the file could not be used. Which block runs, and what kind of result can the function provide?

  1. 1
    Locate the risky operation

    The file operation is the expected point of failure, so it belongs in the focused try block.

  2. 2
    Trace the failure

    Because the file is missing, the operation raises an exception. Python leaves the try path and jumps to the except block.

  3. 3
    Read the handler's response

    The except block now controls what happens next. It can provide a useful fallback response or end the function gracefully.

  4. 4
    Contrast success

    If the file operation succeeds instead, Python skips the except block and the function follows its normal later behavior.

Result

A missing file follows the exception path; a usable file follows the success path. The handler prevents the expected problem from automatically causing the program to crash.

The important distinction is not that the operation always fails. The point of try-except is to define what the function should do in either case: continue with its normal behavior after success, or use the handler's planned response after an exception.

Mistakes in Error Handling

  • Common mistake

    Assuming the except block always runs

    What it looks like

    Treating the handler as if it were the next normal step after every try block.

    Why it fails

    Python skips the except block when no exception occurs.

    Do this instead

    Trace the try block first. Choose the except path only when a statement in the try block raises an exception.

  • Common mistake

    Protecting an unnecessarily large sequence

    What it looks like

    Putting unrelated operations inside the same try block as the operation that might fail.

    Why it fails

    The source recommends keeping the try block focused on the operation that might fail.

    Do this instead

    Place the expected failure point and the statements directly involved in it inside the focused try block.

  • Common mistake

    Treating every error as unexpected

    What it looks like

    Ignoring the possibility of invalid user input or a missing file.

    Why it fails

    These are examples of expected errors that try-except can handle.

    Do this instead

    Identify expected failure situations and plan a response in the except block.

  • Common mistake

    Catching an exception without deciding what should happen next

    What it looks like

    Adding an except block but giving the function no useful response.

    Why it fails

    Catching the exception gives the function control, but the handler still needs a deliberate response.

    Do this instead

    Use the handler to fix the problem, try again, or end gracefully.

Writing the Response

  1. 1
    Identify the operation that is expected to fail, such as processing user input or opening a file.
  2. 2
    Put that operation in a focused try block.
  3. 3
    Predict the normal path: if the try statements succeed, the except block is skipped.
  4. 4
    Design the exception path: if an exception occurs, the except block handles the situation.
  5. 5
    Choose the handler's outcome: fix the problem, try again, provide a fallback result, or end gracefully.
  6. 6
    Check that the function's behavior is understandable on both the success path and the exception path.

Try the Trace Yourself

EASY

A function places a user-input operation inside a try block. In the first run, the input is valid. In the second run, the input is invalid and raises an exception. For each run, describe which block executes, whether the except block is skipped, and what kind of response the handler could provide in the second run.

Hints
  • Start by tracing the try block.
  • The success path skips the except block.
  • The exception path jumps to the except block, where the function can respond instead of crashing.

A strong answer should distinguish the two paths rather than saying only that the error is handled. On the valid-input run, the try operation succeeds and the except block is skipped. On the invalid-input run, Python jumps to the except block, where the function can provide a fallback, try again, fix the problem, or end gracefully.

Summary

  1. 1
    Python executes the try block first.
  2. 2
    When the try block succeeds, Python skips the except block.
  3. 3
    When a statement in the try block raises an exception, Python jumps to the except block.
  4. 4
    Try-except is useful for expected errors such as invalid user input and missing files.
  5. 5
    The except handler gives the function control to fix the problem, try again, return a fallback response, or end gracefully.

At a glance

  • A try-except block protects a focused sequence of statements that may produce an expected error.
  • Successful try-block execution skips the except block.
  • An exception in the try block changes control flow to the except handler.
  • The handler lets a function respond deliberately instead of crashing, including by fixing the problem, trying again, or ending gracefully.

Related concepts

More concepts starting with W