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 ?
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 ?
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
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.
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
readLine() throws IOException which is checked exception should be either thrown or handled at compile time see Oracle documentation