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 ?

2
  • 4
    readLine throws a checked exception Commented Sep 11, 2013 at 16:32
  • @WinCoder I gave a quick explanation of checked and unchecked exception here. Commented Sep 11, 2013 at 16:40

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

why would a console interaction method throw an exception ?
@WinCoder if an I/O error occurs while reading the stream, an IOException will be thrown, with the available details in the exception object.
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)
1

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.