Question

In this simple program, why do I have to handle an exception ?

public static void main (String args[ ]) throws IOException
   {
        BufferedReader in = new BufferedReader(
        new InputStreamReader(System.in));

    System.out.print("Insert something : ");
        System.out.println("You inserted : "+in.readLine());    
   }
Was it helpful?

Solution

Reading from stdin is very unlikely to cause any kind of IOException. The BufferedReader doesn't know that, though, it assumes whatever it is wrapping will throw IOException and it is just passing it along. I would think about using the java.util.Scanner class instead, to avoid the annoyance of the BufferedReader checked exceptions here.

The JVM will handle closing stdin for you when the program terminates, so closing the reader shouldn't be an issue, except that you may end up needing to flush the BufferedReader to get all its contents. This is another reason to prefer Scanner.

For a small program it can be fine to let the main method throw exceptions, those will get written to the console (specifically, to stderr). As long as that is the behavior you want, throwing the IOException here is ok. In real life a program could be executed from a shell script and the shell script could redirect the program's output to a file, so that anything thrown by the program would be logged.

OTHER TIPS

Because of the contract of the close() method. From the JavaDoc:

Closes the stream and releases any system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.

When the buffered stream is closed, the BufferedReader can't read anything more and will notify the caller about this fact by throwing an IOException.

You need to handle IOException because it is a checked exception and method in.readLine() specifically declares it with a throws clause. That means IO Exception can be thrown at run time, so you should handle it. Hope this helps.

BufferReader#readLine() method throws IOException so if you use this method you should either use it inside a try-catch block or add the throws IOException to the method in which you use it.

Quoting from java doc

enter image description here

And to learn more about the exception handling in general (of course in java) please read java doc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top