Reputation: 11
I'm new to Java and programming and trying to understand catch blocks. I've been playing around with this bit of code.
public class Main {
public static void main(String[] args) {
// create a new buffered reader to read user input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name;
try{
name = br.readLine();
}
catch(IOException e){
System.out.println("There was a problem");
return;
}
System.out.println("Hello " + name );
}
}
As I understand it, I have to use a catch block with BufferedReader to catch the IO Exception, however when I try to execute the catch block by just hitting return, it doesn't execute the catch block and print out the message, rather it prints out last line, with name empty. I've tried putting Exception rather than IOException. If I put Exception rather than IOException I get exit status 143, rather than it executing catch block.
Can anyone suggest where I'm going wrong, or probably more importantly what I'm not understanding?
Upvotes: 0
Views: 101
Reputation: 1
If you want to force the user to enter their name
then you can do this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = "";
while (name.isEmpty()) {
try {
System.out.print("What is your name?");
name = br.readLine().trim();
if (name.isEmpty()) {
System.out.println("Name cannot be empty. Please try again.");
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
System.out.println("Hello, " + name + "!");
Upvotes: 0