I can "fix" the below exception with a try-catch loop but I cannot understand the reason.
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);
}
}
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With