I have the following java code:
System.out.print("fPlease Enter an integer: "); while(!validInt){ try{ number = kb.nextInt(); validInt = true; }catch(InputMismatchException e){ System.out.print("Pretty please enter an int: "); System.out.print(e.getMessage()); kb.nextLine(); continue; ) kb.nextLine(); }
how can I set e.getMessage() so that System.out.println(e.getMessage()) will print “Pretty please enter an int: “
Advertisement
Answer
You only set the message when the exception is created, it’s an argument to the constructor. In your case it would have been nice if the InputMismatchException was created like this:
tnrow new InputMismatchException(“Pretty please enter an int: “)
Since you probably aren’t creating the InputMismatchException, you can’t set it’s message, however inside a catch you can do something liket this:
catch(InputMismatchException ime){ throw new IllegalArgumentException("Pretty please enter an int: "); }
Then someone above you can catch that exception and will have an appropriate error message.
This is obviously a bit awkward which is why it usually isn’t used this way.
Note:
You aren’t usually supposed to re-use java exceptions but create your own. This is pretty annoying and I almost always re-use either IllegalArgumentException or IllegalStateException Because those are good, reusable exceptions and describe most of the reasons you’d want to throw in general code for “Catch and rethrow” exceptions as I discussed above.