Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly use Exception method getMessage

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: "

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading