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.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap