Alex Rivera | Logout

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

Asked 2010-04-13T12:58:17.597
10

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);
  }
 }
}
Edit
Report

1 Answer

1

It is thrown if an exceptional situation occurs with the I/O, for example the source of the stream is no longer available.

In such cases your program should be able to recover. Either by re-reading the source, or by using some defaults, or by alerting the user about the problem.

You are forced to catch it, because it is a checked exception, and you are supposed to be able to recover from those.

Of course, you have the option to declare that the current menthod throws this exception to caller methods, but you will have to catch it eventually (or let it bubble up to the main method, when it is simply printed on the console and the program execution stops)

answered 2010-04-13T13:03:49.177

Your Answer