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

no exceptionexception occurshandler respondstry blockexecute statementslater statementsexcept skippedexcept blockhandle exceptionchosen responsefix, retry, or endgracefully
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.

protectsif exceptionif successfulrunstrybegin protected sequencerisky operationmay raise exceptionexceptbegin responsehandler responserespond to errorlater statementsafter try-except
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.

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

Tracing a Missing File

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?

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

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

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.

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

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

  • Assuming the except block always runs

    Python skips the except block when no exception occurs.

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

  • Protecting an unnecessarily large sequence

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

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

  • Treating every error as unexpected

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

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

  • Catching an exception without deciding what should happen next

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

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

Writing the Response

  1. Identify the operation that is expected to fail, such as processing user input or opening a file.
  2. Put that operation in a focused try block.
  3. Predict the normal path: if the try statements succeed, the except block is skipped.
  4. Design the exception path: if an exception occurs, the except block handles the situation.
  5. Choose the handler's outcome: fix the problem, try again, provide a fallback result, or end gracefully.
  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. Python executes the try block first.
  2. When the try block succeeds, Python skips the except block.
  3. When a statement in the try block raises an exception, Python jumps to the except block.
  4. Try-except is useful for expected errors such as invalid user input and missing files.
  5. The except handler gives the function control to fix the problem, try again, return a fallback response, or end gracefully.

Key Takeaways

  • 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.