Open In App

Why Does BufferedReader Throw IOException in Java?

Improve
Improve
Like Article
Like
Save
Share
Report

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 BufferedReader Class
 
import java.io.*;
 
class GFG {
 
    // Define 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.

 


Last Updated : 30 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads