views:

521

answers:

3

I have the following simple code:

import java.io.*;
class IO {
    public static void main(String[] args) {    
       BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));    
       String userInput;    
       while ((userInput = stdIn.readLine()) != null) {
          System.out.println(userInput);
       }
    }
}

And I get the following error message:

----------
1. ERROR in io.java (at line 10)
    while ((userInput = stdIn.readLine()) != null) {
                        ^^^^^^^^^^^^^^^^
Unhandled exception type IOException
----------
1 problem (1 error)roman@roman-laptop:~/work/java$ mcedit io.java 

Does anybody have any ideas why? I just tried to simplify the code given on the sum web site (here). Did I oversimplify?

+3  A: 

You should add "throws IOException" to your main method:

public static void main(String[] args) throws IOException {

You can read a bit more about checked exceptions (which are specific to Java) in JLS.

Marcin
+2  A: 

Java has a feature called "checked exceptions". That means that there are certain kinds of exceptions, namely those that subclass Exception but not RuntimeException, such that if a method may throw them, it must list them in its throws declaration, say: void readData() throws IOException. IOException is one of those.

Thus, when you are calling a method that lists IOException in its throws declaration, you must either list it in your own throws declaration or catch it.

The rationale for the presence of checked exceptions is that for some kinds of exceptions, you must not ignore the fact that they may happen, because their happening is quite a regular situation, not a program error. So, the compiler helps you not to forget about the possibility of such an exception being raised and requires you to handle it in some way.

However, not all checked exception classes in Java standard library fit under this rationale, but that's a totally different topic.

jkff
A: 

try again with this code snippet.

import java.io.*; class IO { public static void main(String[] args) {

   try{

       BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));    
       String userInput;    
       while ((userInput = stdIn.readLine()) != null) {
          System.out.println(userInput);
       }catch(IOException ie){
         ie.printStackTrace();
        }
      }
   }
}

use or try-catch-finally is better than throws in the case of error finding or say debugging.

Parth