PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 5, 2022

[FIXED] How to properly use Exception method getMessage

 August 05, 2022     exception, getmessage, java     No comments   

Issue

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


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.



Answered By - Bill K
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing