Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Exception Handling
Next article icon

Handling EOFError Exception in Python

Last Updated : 28 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, an EOFError is raised when one of the built-in functions, such as input() or raw_input() reaches the end-of-file (EOF) condition without reading any data. This commonly occurs in online IDEs or when reading from a file where there is no more data left to read. Example:

Python
n = int(input()) print(n * 10) 

Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 1, in <module>
n = int(input())
~~~~~^^
EOFError: EOF when reading a line

Explanation: input() reads user input as a string. If the input is empty (EOF reached), it returns ”, and int(”) raises a ValueError since an empty string cannot be converted to an integer.

When does EOFError occur?

Example 1: sys.stdin.read() reads input from the standard input (stdin) until EOF is reached. If no input is provided, an EOFError is raised.

Python
import sys  data = sys.stdin.read()  if not data:  # If no input is provided     raise EOFError("EOFError: No input received from stdin")  print(data) 

Output:

Traceback (most recent call last): 
File "script.py", line 6, in <module>
raise EOFError("EOFError: No input received from stdin")
EOFError: No input received from stdin

Explanation: Here, sys.stdin.read() waits for input. If no input is given (such as in an automated script without input redirection), it raises EOFError.

Example 2: Using input() inside a loop:

Python
while True:     user_input = input("Enter something: ")     print("You entered:", user_input) 

Output

Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 2, in <module>
user_input = input("Enter something: ")
EOFError: EOF when reading a line

Explanation: This program enters a loop and prompts the user with “Enter something:”, waiting for input. However, instead of providing a value, the user presses Ctrl+Z (on Windows) or Ctrl+D (on Linux/macOS), which sends an End of File (EOF) signal to the program. Since the input() function expects a valid input but receives an EOF instead, it is unable to process the request, leading to an EOFError.

Handling EOFError using exception handling

1. Handling EOFError with default values

When using input(), if an EOFError occurs due to the absence of user input, it can be handled by providing a default value to ensure the program continues executing without interruption.

Python
try:     n = int(input("Enter a number: ")) except EOFError:     n = 0  # Assigning a default value     print("No input provided, setting default value to 0.")  print("Result:", n * 10) 

Output
Enter a number: No input provided, setting default value to 0. Result: 0 

Explanation: If the user does not enter a value and an EOFError occurs, the exception is caught and a default value of 0 is assigned to n.

2. Handling EOFError while reading from a file

When reading a file line by line using readline(), the function returns an empty string (”) when the end of the file (EOF) is reached. Instead of raising an exception, the program can check for an empty line and exit the loop gracefully.

Python
try:     with open("sample.txt", "r") as file:         while True:             line = file.readline()             if not line:  # EOF reached                 break             print(line.strip()) except FileNotFoundError:     print("Error:'sample.txt' was not found.") 

Output
Error: The file 'sample.txt' was not found. 

Explanation: In this case, readline() reads one line at a time. When there are no more lines to read, it returns an empty string (”), which is used as the condition to exit the loop. Although an EOFError is unlikely in this scenario, handling file reading carefully prevents errors when processing large files.

3. Handling EOFError While Using sys.stdin.read()

To handle EOFError when using sys.stdin.read(), we can catch the exception and provide a meaningful error message instead of abruptly terminating the program.

Python
import sys  try:     data = sys.stdin.read()     if not data.strip():         raise EOFError     print("User input:", data) except EOFError:     print("EOFError: No input detected!") 

Output:

EOFError: No input detected!

Explanation: This code reads input from sys.stdin.read(). If no input is detected, an EOFError is raised and caught, displaying an appropriate message instead of crashing the program.



Next Article
Python Exception Handling

R

rowdyninja
Improve
Article Tags :
  • Python
  • Python-exceptions
Practice Tags :
  • python

Similar Reads

  • Python Exception Handling
    Python Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example: Hand
    7 min read
  • Handling OSError exception in Python
    Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as "file not found" or "disk full". Below
    2 min read
  • Multiple Exception Handling in Python
    Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they
    3 min read
  • Handling NameError Exception in Python
    Prerequisites: Python Exception Handling There are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are : 1. Misspelled built-in functio
    2 min read
  • Handling TypeError Exception in Python
    TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise a TypeError. ExamplesThe general causes for TypeErro
    3 min read
  • EnvironmentError Exception in Python
    EnvironmentError is the base class for errors that come from outside of Python (the operating system, file system, etc.). It is the parent class for IOError and OSError exceptions. exception IOError - It is raised when an I/O operation (when a method of a file object ) fails. e.g "File not found" or
    1 min read
  • Errors and Exceptions in Python
    Errors are problems in a program that causes the program to stop its execution. On the other hand, exceptions are raised when some internal events change the program's normal flow. Syntax Errors in PythonSyntax error occurs when the code doesn't follow Python's rules, like using incorrect grammar in
    3 min read
  • Python IMDbPY - Error Handling
    In this article we will see how we can handle errors related to IMDb module of Python, error like invalid search or data base error network issues that are related to IMDbPY can be caught by checking for the imdb.IMDbErrorexceptionIn order to handle error we have to import the following   from imdb
    2 min read
  • Error Handling in Python using Decorators
    Decorators in Python is one of the most useful concepts supported by Python. It takes functions as arguments and also has a nested function. They extend the functionality of the nested function. Example: C/C++ Code # defining decorator function def decorator_example(func): print("Decorator call
    2 min read
  • Concrete Exceptions in Python
    In Python, exceptions are a way of handling errors that occur during the execution of the program. When an error occurs Python raises an exception that can be caught and handled by the programmer to prevent the program from crashing. In this article, we will see about concrete exceptions in Python i
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences