Concepts / Try-Except Blocks: Catching and Handling Errors

Try-Except Blocks: Catching and Handling Errors

exit() terminates the entire program immediately and never returns to any caller.

  • Programming
Interactive lab

Try it: try / except / else / finally

How an exception jumps out of a try block to the first matching except clause, when else runs, and why finally always runs.

How it works

  1. Statements in try run until one raises an exception; the rest of try is skipped.
  2. Python checks the except clauses in order and runs the first one whose type matches.
  3. If nothing was raised, the else block runs instead.
  4. finally runs in every case.

Default run (9 steps): Call safe_divide('4'). … Return 25.0. Output was: Worked: 25.0 / Done.

Simplified: One fixed function; int() and / are modelled exactly (including how Python prints floats), but nothing is executed as Python.

Educational simulation

Loading the simulation…

When Continuing Is Not Safe

Error handling does not always mean recovering and continuing. If a program cannot open a file that it needs, the remaining work may not be possible. In that situation, an except block can print an error message and use exit() to stop the entire program cleanly. The important idea is that exit() does not pause one function or return to a caller. It terminates the complete program immediately.

Use exit() for an unrecoverable error: report what went wrong, then stop instead of allowing the program to continue without the required file or data.

The Program-Wide Effect

Imagine that several functions are active: one function called another, which called another, and the current function encounters an error. A return statement would pass control back to the function that called the current function. exit() behaves differently. It terminates the entire program, so the current function does not continue, its caller does not regain control, and the rest of the program does not continue either.

exit() terminatesno returnCurrent functionexecutes exit()Caller functiondoes not regain controlEntire programterminates
What happens to the current function, its callers, and the rest of the program when exit() is executed?

Return Compared with Exit

StatementControl-flow resultAppropriate role
returnPasses control back to the function that called the current functionUse when the caller should regain control
exit()Terminates the entire program and never returns to any callerReserve for an unrecoverable error
passes control toterminatesreturnCaller functionexit()Entire program
How does control flow differ when a function uses return versus when the program uses exit()?

A Failed File Operation

The source describes a program that asks the user for a filename, tries to open the file, and counts lines beginning with Subject:. If the file cannot be opened, the program prints an error message and exits. The following is a generated Python illustration of that behavior.

python

Tracing an unavailable file

What happens when the requested file cannot be opened?

Request: The program asks the user for a filename.

Try: The file-opening operation is placed in the try block.

Failure: If the file cannot be opened, control moves to the except block.

Message: The except block prints an error message so the user knows why processing cannot continue.

Termination: exit(1) terminates the entire program instead of returning to a caller or continuing to count lines.

The program stops cleanly after reporting the file error; the line-counting work does not continue.

filenamecannot opencontrol moves to exceptexit(1)Filenameuser provides a nameOpen filetry blockFile errorfile cannot be openedError messageexcept blockProgram terminationexit(1)
After a file operation fails, how does control move from the try block to the except block and then to program termination?

Exit Status Codes

When a program exits, exit() sends a status code to the operating system. Calling exit() without an argument sends status code 0, which communicates success or normal termination. An integer can also be passed to exit(). A non-zero status code typically communicates that an error occurred. In the file example, exit(1) communicates that the program stopped because the file operation failed.

sends 0sends non-zero codeexit()status code 0Operating systemsuccess or normalterminationexit(1)non-zero statusOperating systemerror occurred
How does an exit status code move from the program to the operating system, and what does each status communicate?
CallStatus codeMeaning communicated
exit()0Success or normal termination
exit(integer)The supplied integerA chosen program status; a non-zero value typically indicates an error
exit(1)1A non-zero error status, such as a failed file operation

Status information sent when the program exits

Mistakes with Program Termination

  • Treating exit() like return

    exit() terminates the entire program and never returns to any caller.

    Fix: Use return when control should pass back to the function that called the current function.

  • Continuing after an unrecoverable file failure

    The required file is unavailable, so the remaining file-processing work cannot proceed as intended.

    Fix: Print an error message and use exit() in the except block when the failure makes continued execution impossible.

  • Ignoring the status code

    exit() with no argument sends status code 0, which communicates success or normal termination.

    Fix: Use a non-zero integer when the program is stopping because an error occurred.

Check the Control Flow

MEDIUM

A program tries to open a required file. The operation fails, the except block prints an error message, and then the block calls exit(2). Explain what happens to the current function, its caller, the rest of the program, and the operating system status.

Hints
  • Compare exit() with return.
  • Remember what a non-zero status code communicates.

What do you think happens?

After exit(2) executes inside the except block, does control return to the caller so that the rest of the program can continue?

  • Yes, because exit() behaves like return
  • No, because exit() terminates the entire program
  • Only if the current function was called directly
Reveal answer

Answer: No, because exit() terminates the entire program.

exit() never returns to any caller. The integer 2 is a non-zero status code, which typically communicates that an error occurred.

Key Takeaways

  1. exit() terminates the entire program immediately and never returns to a caller.
  2. return passes control back to the function that called the current function; exit() ends the complete program.
  3. A file-operation failure can be handled by printing an error message in an except block and then calling exit().
  4. exit() with no argument sends status code 0 for success or normal termination.
  5. A non-zero status code typically communicates that an error occurred.

Key Takeaways

  • exit() stops the entire program rather than returning to a caller.
  • Use exit() in an except block when an error, such as an unavailable required file, is unrecoverable.
  • Use return when the caller should regain control.
  • Status code 0 communicates success or normal termination; a non-zero code typically communicates an error.