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 ?
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.
IOException will be thrown, with the available details in the exception object.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)readLine() throws IOException which is checked exception should be either thrown or handled at compile time see Oracle documentation
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
readLinethrows a checked exception