Fix: EOFError Exception in Python

EOFError (EOF = End of File) exception is a concrete exception in Python that is raised when the input() function encounters an end-of-file condition (EOF) without reading any data.

Let us take a look at an example.

Example:
user_input = input("Enter your Name: ")
print(user_input)
python3 example.py

Enter your Name: Traceback (most recent call last):
  File "/Users/c2ctechtv/Desktop/example.py", line 1, in <module>
    user_input = input("Enter your Name: ")
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^
EOFError
% python3 example.py
Enter your Name: Traceback (most recent call last):
  File "/Users/c2ctechtv/Desktop/example.py", line 2, in <module>
    user_input = input("Enter your Name: ")
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^
EOFError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/c2ctechtv/Desktop/example.py", line 5, in <module>
    print("Please provide a valid input: "+ e)
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
TypeError: can only concatenate str (not "EOFError") to str
Python EOFError Example

Fix EOFError:

We can handle the EOFError by surrounding the code with try/except block.

try:
    user_input = input("Enter your Name: ")
    print(user_input)
except EOFError as e:
    print("An EOFError occurred:", e)
    print("Please provide a valid name.")
except Exception as e:
    print("An error occurred:", e)
python3 example.py

Enter your Name: An EOFError occurred: EOF when reading a line
Please provide a valid name.

References:

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!