Try-Except Blocks: Catching and Handling Errors
exit() terminates the entire program immediately and never returns to any caller.
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
- Statements in try run until one raises an exception; the rest of try is skipped.
- Python checks the except clauses in order and runs the first one whose type matches.
- If nothing was raised, the else block runs instead.
- 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.
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.
Return Compared with Exit
| Statement | Control-flow result | Appropriate role |
|---|---|---|
| return | Passes control back to the function that called the current function | Use when the caller should regain control |
| exit() | Terminates the entire program and never returns to any caller | Reserve for an unrecoverable error |
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.
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.
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.
| Call | Status code | Meaning communicated |
|---|---|---|
| exit() | 0 | Success or normal termination |
| exit(integer) | The supplied integer | A chosen program status; a non-zero value typically indicates an error |
| exit(1) | 1 | A 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
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?
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
- exit() terminates the entire program immediately and never returns to a caller.
- return passes control back to the function that called the current function; exit() ends the complete program.
- A file-operation failure can be handled by printing an error message in an except block and then calling exit().
- exit() with no argument sends status code 0 for success or normal termination.
- 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.