How to catch EOFError Exception in Python?


An EOFError is raised when a built-in function like input() or raw_input() do not read any data before encountering the end of their input stream. The file methods like read() return an empty string at the end of the file.

The given code is rewritten as follows to catch the EOFError and find its type.

Example

#eofError.py
try:
while True:
data = raw_input('prompt:')
print 'READ:', data
except EOFError as e:
print e
Then if we run the script at the terminal
$ echo hello | python eofError.py

Output

prompt:READ: hello
prompt:EOF when reading a line


Updated on: 12-Feb-2020

640 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements