Yodism
Yodism

Reputation: 247

When catch block statements will appear

I'm writing programs for 2 years as a student. I'm just curious when the catch statements will appear. I tried everything to make my program output the statements inside the catch block but I fail. Any ideas?

try{
    System.out.print("Enter a sentence: ");
      String sentence = dataIn.readLine();
      String res = sentence.replaceAll(" ", "");
    System.out.println(res);
  }catch(IOException e){
    e.printStackTrace();
    System.err.println(e);
  }
}

Upvotes: 0

Views: 175

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201447

You could throw new IOException like

try {
    throw new IOException("Like this");
} catch (IOException e) {
    e.printStackTrace();
    System.err.println(e);
}

Output is

java.io.IOException: Like this
    at com.stackoverflow.Main.main(Main.java:8)
java.io.IOException: Like this

Upvotes: 1

Gagravarr
Gagravarr

Reputation: 48326

It will be triggered when the code inside it throws an IOException

You can force that to happen quite simply with something like this:

try{
    System.out.print("Enter a sentence: ");
    String sentence = dataIn.readLine();
    String res = sentence.replaceAll(" ", "");
    System.out.println(res);
    throw new IOException("Testing");
} catch(IOException e) {
    e.printStackTrace();
    System.err.println(e);
}

Whatever your dataIn object is could well throw one too, eg if the stream it was reading from gave an error

Upvotes: 1

Related Questions