0
DataInput in = new DataInputStream(System.in);
System.out.println("What is your name");
String name = in.readLine();

The error says "Unhandled IO Exception". What's wrong with this code ?

Win Coder
  • 6,628
  • 11
  • 54
  • 81
  • 4
    `readLine` throws a checked exception – Reimeus Sep 11 '13 at 16:32
  • @WinCoder I gave a quick explanation of checked and unchecked exception [here](http://stackoverflow.com/questions/8423700/how-to-create-a-custom-exception-type-in-java/8423743#8423743). – Laf Sep 11 '13 at 16:40

4 Answers4

4

Unhandled IO Exception

either catch IOException or declare it to throw, readLine() declares that it could throw this exception so your code need to handle/throw it

jmj
  • 237,923
  • 42
  • 401
  • 438
2

You must surround the call to in.readLine () with a try/catch.

DataInput in = new DataInputStream(System.in);
System.out.println("What is your name");

try {
    String name = in.readLine();
} catch (IOException ioex) {
    // Handle exception accordingly
}

Or you could add a trows IOException clause to your method signature, which means the calling method will have to handle the exception (with the try/catch block).

As per the Javadoc entry, the the readLine () method is deprecated, and you should use a BufferedReader instead.

Laf
  • 7,965
  • 4
  • 37
  • 52
  • why would a console interaction method throw an exception ? – Win Coder Sep 11 '13 at 16:33
  • @WinCoder if an I/O error occurs while reading the stream, an `IOException` will be thrown, with the available details in the exception object. – Laf Sep 11 '13 at 16:37
  • 1
    Could be any number of reasons. Ultimately, it doesn't matter though, because the method is declared as `throws IOException`, you are required, one way or another, to handle the exception, whether by catching it or by declaring your method `throws IOException` (or some superclass of `IOException`) – StormeHawke Sep 11 '13 at 16:38
1

This method readLine() throws IOException that is a checked Exception. So You have two options catch it and handle it and/or in method declaration add throws keyword

Example:

public void throwsMethod() throws IOException{
  DataInput in = new DataInputStream(System.in);
  System.out.println("What is your name");
  String name = in.readLine();
  .
  .
}

public void handleMethod(){
  DataInput in = new DataInputStream(System.in);
  System.out.println("What is your name");
  String name=null;
  try{
    name = in.readLine();
  }catch(IOException){
   //do something here
  }
  .
  .
}

For more information read this oracle article Exceptions

nachokk
  • 14,363
  • 4
  • 24
  • 53
1

readLine() throws IOException which is checked exception should be either thrown or handled at compile time see Oracle documentation

ankit
  • 4,919
  • 7
  • 38
  • 63