Skip to content
Related Articles

Related Articles

Why Does BufferedReader Throw IOException in Java?
  • Last Updated : 07 Jan, 2021

IOException is a type of checked exception which occurs during input/output operation. BufferedReader is used to read data from a file, input stream, database, etc. Below is the simplified steps of how a file is read using a BufferedReader in java.

  1. In RAM a buffered reader object is created.
  2. Some lines of a file are copied from secondary memory ( or Hard disk) and store in the buffer in the RAM.
  3. Now with the help of a buffered reader object our program can read the buffer in RAM.
  4. If all the lines are read then next some lines of the file are copied from secondary memory into the buffer.

Buffered Reader Work Flow Overview

This file system reading can fail at any time for many reasons. It may occur due to the file deleted or viruses in the file. Sometimes BufferedReader takes data from a network stream where the reading system can fail at any time.

So this type of error can occur in input operation when a BufferedReader is used. This is why a buffered reader throws IOException.

Below is an example of BufferedReader use

Input: a = 5, b = 3
Output: 8

Implementation:



Java




// This is an example of use of BuffereReader Class
  
import java.io.*;
  
class GFG {
  
    // Difine BufferedReader object
    static BufferedReader br = new BufferedReader(
        new InputStreamReader(System.in));
  
    // If you delete 'throws IOException'
    // you will get an error
    public static void main(String[] args)
        throws IOException
    {
        int a = Integer.parseInt(br.readLine());
        int b = Integer.parseInt(br.readLine());
        System.out.println(a + b);
    }
}

Output:

If the file is deleted from the server-side while reading the input from the server-side, IOException is thrown.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :