Search code examples
javaexceptionioexception

Java: what are IOEXceptions in BufferedReader's readLine() for?


I can "fix" the below exception with a try-catch loop but I cannot understand the reason.

  1. Why does the part "in.readLine()" continuosly ignite IOExceptions?
  2. What is really the purpose of throwing such exceptions, the goal probably not just more side effects?

Code and IOExceptions

$ javac ReadLineTest.java 
ReadLineTest.java:9: unreported exception java.io.IOException; must be caught or declared to be thrown
  while((s=in.readLine())!=null){
                      ^
1 error
$ cat ReadLineTest.java 
import java.io.*;
import java.util.*;

public class ReadLineTest {
 public static void main(String[] args) {
  String s;
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  // WHY IOException here?
  while((s=in.readLine())!=null){
   System.out.println(s);
  }
 }
}

Solution

  • The basic idea is that a BufferedReader delegates to a different kind of Reader, so it is passing on that exception.

    That different kind of Reader can read from some kind of volatile external resource, say a file system in the case of FileReader. A file system read can fail for many reasons at any time. (The situation is worse if the Reader is getting its underlying data from a Network Stream). The file could get deleted out from under you (depending on the file system and OS involved).

    Because you cannot predict what will happen with code, you get a checked exception - the point being that the API is telling you that you should think about the fact that this operation may not work out even if there is nothing wrong with your code.