Exception Handling with Try-Except
The exception is raised at the input() call itself, so execution does not continue past that call unless an exception handler catches it.
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 Input Stops Normally
The input() function normally waits for a line of text followed by the Enter key. However, a user or an input source can signal that no more input is available. This is called end-of-file, or EOF. When input() encounters EOF, Python raises an EOFError instead of returning a string.
EOF is a signal that no more input is available. It is not an empty line.
What do you think happens?
What happens when input() receives an EOF signal instead of a line of text?
Reveal answer
It raises EOFError.
An EOF signal tells input() that no more input is available, so input() does not return a string. Python raises EOFError, interrupting the normal flow of execution.
Tracing the EOF Signal
The signal travels through several stages. When Ctrl-D is pressed at a terminal, the terminal recognizes it as a special control sequence and sends an EOF marker to the input stream. The input() function is reading from that stream. When it detects the marker, it stops waiting for more data and raises EOFError. The exception is raised at the input() call itself, so execution does not continue past that call unless an exception handler catches it.
If no handler is present, the exception terminates the program and Python prints a traceback. The traceback identifies the input() call because the program never got past that line.
Empty Input Versus EOF
Pressing Enter without typing any characters produces an empty line. In that case, input() returns the empty string, written as ''. The program continues, and a variable receiving the result gets that string. Pressing Ctrl-D on a typical terminal, or Ctrl-Z on Windows, sends an EOF signal instead. In that case, input() does not return a string; it raises EOFError.
| User action | What input() receives | Result | Does normal execution continue? |
|---|---|---|---|
| Press Enter with no text | An empty line | The empty string '' | Yes |
| Press Ctrl-D | An EOF signal | EOFError is raised | Only if the exception is caught |
| Press Ctrl-Z on Windows | An EOF signal | EOFError is raised | Only if the exception is caught |
The key difference is whether input() returns a string or raises EOFError.
Catching EOFError
A try-except block gives the program a defined response when input() encounters EOF. Put the input() call inside try. Then use except EOFError to describe what the program should do when the EOF signal arrives. Instead of terminating with an unhandled traceback, execution moves from the input() call to the except block.
In this example, a regular line of input is assigned to response. If the input source sends EOF instead, Python raises EOFError and skips directly to the except block. The message begins with a newline so it appears on a fresh line, because Ctrl-D does not produce a newline. After the except block finishes, the program exits normally without an unhandled traceback.
Worked Execution Trace
Following an EOF Signal
A program calls input() inside a try block. The user presses Ctrl-D instead of entering text. Trace the program's execution.
- 1The program waits
Execution reaches
input(), which waits for a line of text followed by Enter. - 2The terminal sends EOF
Ctrl-D signals that no more input is available. The program does not receive a string.
- 3Python raises EOFError
input()detects the EOF marker and raises EOFError at theinput()call. - 4Normal flow is interrupted
The program does not continue with statements that would have followed the
input()call inside the try block. - 5The handler runs
Because an except EOFError handler exists, execution jumps to that handler, which can print a response or perform another defined action.
- 6The program finishes normally
The handled exception does not produce an unhandled traceback.
EOF changes the path of execution from the input() call to the matching except block.
response = input("Enter a response: ")EOF reaches input() with no exception handler, so the program terminates with a traceback.
try:
response = input("Enter a response: ")
except EOFError:
print("\nNo more input was available.")EOF reaches input(), the except block handles EOFError, and the program responds without an unhandled traceback.
Mistakes with EOF
Common mistake Treating an empty line as EOF
What it looks likeAssuming that pressing Enter without typing means input() will raise EOFError.
Why it failsAn empty line is valid input.
input()returns the empty string ''.Do this insteadDistinguish the returned empty string from the EOF signal that causes EOFError.
Common mistake Expecting input() to return a special EOF string
What it looks likeAssuming the variable will receive a value that represents end-of-file.
Why it failsWhen EOF is detected,
input()does not return a string. It raises EOFError.Do this insteadHandle EOF with an except EOFError block.
Common mistake Putting input() outside the protected try block
What it looks likeUsing a try-except block elsewhere while leaving the input() call unprotected.
Why it failsThe exception is raised at the
input()call, so execution needs a matching handler that protects that call.Do this insteadPlace the input() call inside try and catch EOFError in except.
Common mistake Ignoring EOF in interactive or repeated input
What it looks likeAllowing an input loop to call input() repeatedly without an EOF handler.
Why it failsAn EOF signal can interrupt normal execution and terminate the program if no handler exists.
Do this insteadPlan a graceful response to EOF, especially in loops or interactive programs.
Check Your Understanding
A program calls input(). The user presses Enter without typing anything. Then consider a second run in which the user signals EOF with Ctrl-D. For each run, state whether input() returns a value or raises an exception, and identify whether execution can continue without an exception handler.
Hints
- An empty line is still a line of input.
- EOF means that no more input is available.
- Ask whether
input()returns a string or raises EOFError.
Expected reasoning: pressing Enter with no text makes input() return ''. The program can continue normally. Pressing Ctrl-D makes input() raise EOFError. Without a handler, the program terminates with a traceback; with an except EOFError handler, execution moves into that handler instead.
Key Takeaways
- EOFError is raised when
input()encounters an end-of-file signal. - Pressing Enter with no text returns the empty string; it does not raise EOFError.
- Ctrl-D, or Ctrl-Z on Windows, signals EOF rather than supplying a string.
- An unhandled EOFError terminates the program and produces a traceback.
- A try-except block can catch EOFError and let the program respond gracefully.