Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
  }
 }
}
like image 766
hhh Avatar asked Apr 13 '10 12:04

hhh


People also ask

Why do we use IO exception?

An IO (Input-Output) Exception is predictably caused by something wrong with your input or output. It can be thrown by most classes in the java.io package for many reasons to prevent errors. For example, using a scanner to read data and receiving an invalid type or writing data into a file that doesn't exist.

What is IO exception Java?

IOException is the base class for exceptions thrown while accessing information using streams, files and directories. The Base Class Library includes the following types, each of which is a derived class of IOException : DirectoryNotFoundException. EndOfStreamException. FileNotFoundException.

Which exception is thrown by readLine () method?

For example, an IOException is a checked exception. Some programs use the readLine() method of BufferedReader for input. This method throws an IOException when there is a problem reading.

What does BufferedReader readLine do in Java?

The readLine() method of BufferedReader class in Java is used to read one line text at a time. The end of a line is to be understood by '\n' or '\r' or EOF.


1 Answers

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.

like image 106
Yishai Avatar answered Nov 02 '22 11:11

Yishai