Hello -

I am trying to catch a NumberFormatException using the code below. However, even though it does perform the System.out.println() in the catch statement when a non-number is entered, it still "blows up" displaying the NumberFormatException with all of its accompanying messy messages in the console. I thought I had it catching the exception properly earlier, but something changed to make it no longer catch it properly. Generally, the code gets text from various specially formatted JTextFields using trim() and must convert them to numbers; but in the case where the user did not enter a number, the exception needs to be caught without displaying the NumberFormatException (of course).

Any help is greatly appreciated!

Thanks,

anthutton

if ( e.getSource() == EnterButton ){
               try{
                   for(int i = 0; i <= 17; i++){
		              //get score in text & convert to int for player1
		              scoreInText[i] = hole[i].getText();
		              scoreInNumber[i] = Integer.parseInt(scoreInText[i].trim());

			          //get score in text & convert to int for player2
		              scoreInText2[i] = hole2[i].getText();
		              scoreInNumber2[i] = Integer.parseInt(scoreInText2[i].trim());

					  //determine lowest score between two players
					  String handicap1InText = handicap1.getText();
					  String handicap2InText = handicap2.getText();
					  handicap1InNumber = Integer.parseInt(handicap1InText.trim());
					  handicap2InNumber = Integer.parseInt(handicap2InText.trim());
					  int adjustment1 = 0;
					  int adjustment2 = 0;
					  int handicapDifference1 = 0;
					  int handicapDifference2 = 0;

					  //account for handicaps player1 
					  //establish the handicapDifference #'s (must be positive)
					  //for calculation needed later
					  handicapDifference1 = (HOLEHANDICAPS[i] - handicap1InNumber) * -1;
					  handicapDifference2 = (HOLEHANDICAPS[i] - handicap2InNumber) * -1;

					  if(handicap1InNumber == 18){
						  adjustment1 = -1;}
					  else if(handicap1InNumber == 36){
						  adjustment1 = -2;}
					  else if(handicap1InNumber < 18 && HOLEHANDICAPS[i] - handicap1InNumber <= 0){
						  adjustment1 = -1;}
					  else if(handicap1InNumber > 18 && handicap1InNumber < 36 &&
					      HOLEHANDICAPS[i] - handicap1InNumber < 0 && HOLEHANDICAPS[i] <=
					      (handicap1InNumber - 18)){adjustment1 = -2;}
				      else if(handicap1InNumber > 18 && handicap1InNumber < 36 && HOLEHANDICAPS[i]
				          - handicap1InNumber < 0 && HOLEHANDICAPS[i] > (handicap1InNumber - 18)){
						   adjustment1 = -1;}

					  //account for handicaps player2
					  if(handicap2InNumber == 18){
						  adjustment2 = -1;}
					  if(handicap2InNumber == 36){
						  adjustment2 = -2;}
					  else if(handicap2InNumber < 18 && HOLEHANDICAPS[i] -
					      handicap2InNumber <= 0){adjustment2 = -1;}
					  else if(handicap2InNumber > 18 && handicap2InNumber < 36
					      && HOLEHANDICAPS[i] - handicap2InNumber < 0 && HOLEHANDICAPS[i] <=
					      (handicap2InNumber - 18)){adjustment2 = -2;}
				      else if(handicap2InNumber > 18 && handicap2InNumber < 36 &&
				          HOLEHANDICAPS[i] - handicap2InNumber < 0 && HOLEHANDICAPS[i] >
				          (handicap2InNumber - 18)){adjustment2 = -1;}

					  scoreInNumber[i] = scoreInNumber[i] + adjustment1;
					  scoreInNumber2[i] = scoreInNumber2[i] + adjustment2;


		              if(scoreInNumber[i] < scoreInNumber2[i]){
						  bestBallScore[i] = scoreInNumber[i];}
						  else{
							  bestBallScore[i] = scoreInNumber2[i];}

					  bestBallScoreNumber[i] = Integer.toString(bestBallScore[i]);
		              hole3[i].setText(bestBallScoreNumber[i]);
			       }
				}
		       catch (NumberFormatException nfe) {
                   System.out.println("Scores are not Complete - Please Verify Scores");
			   }
Member Avatar for ede

Hi,

Actually your question doesn't make sense. As i can understand, NumberFormatException should be caugth and not printed any message to terminal however you also want to know about wrong inputs!!!

if you work with console there is no solution. But you can give message with JOptionPane window.

JOptionPane.showMessage(...)

1. Is it exactly a NumberFormatException that still displays, or something similar?
2. When the Exception displays, is the line number within the try clause that you think it should be?

Hi JamesCherrill -

Thank you very much for your reply. Yes, it still shows a NumberFormatException. I tried catching an IllegalArgumentException but to no avail. That was just kind of a wild guess on my part anyway, and since I believe an IllegalArgumentException is more general than the NumberFormatException, I really should not have expected it to help. And it didn't!

And yes, the line number within the try clause where the exception is thrown is a line number where I think it should be. It occurs on one of my parseInt statements. More specifically, in multiple attempts, it seems to always occur on the first parseInt statement within the try clause. Do you have any ideas on a fix?

Thanks again for any help.

anthutton

It's a puzzle. Try catching Exception - that will get it no matter what it is!

I already tried that too. It doesn't work. The true puzzle is that it runs the code in the catch yet still displays the exception/blows up with all of the detail. Do you know if the exception occurs multiple times sequentially (i.e. multiple back-to-back lines to parseInt), that it somehow cannot catch all of them? I'm at a loss on this one.

Thanks again.

anthutton

Well we can't run the code since it refers to other things. Your goal is to catch and handle problems in the way you want. It's catching things correctly (not letting bad input go by the point where you think the bad input is), but it's not handling it the way you want. It sounds like you agree that it IS in fact bad input and should be caught? In other words, nothing that you think is GOOD input is getting by? You have a parseInt that is working on a String that isn't a number, so it's caught there. Do you know what String it is catching and is that the String that you believe should be there? Just trying to clarify the situation since again, we have no way of running it.

Hi VernonDozier -

Thanks for your reply. You bring up a good point w/regards to how it is handled by me. I don't want the program to exit when the exception occurs. As the code indicates, I just want to execute a System.out.println statement when the exception is caught, which it does. However, it then goes on to display the NFE exception with all of its detail. Isn't the point of catching the exception to allow me (the programmer) to determine how it should be handled without displaying the exception information? That's what is so puzzling; it handles it in the manner I have chosen, yet goes onto display the exception information. Hmmmmm...

Thanks for any help!

anthutton

Hi VernonDozier -

Thanks for your reply. You bring up a good point w/regards to how it is handled by me. I don't want the program to exit when the exception occurs. As the code indicates, I just want to execute a System.out.println statement when the exception is caught, which it does. However, it then goes on to display the NFE exception with all of its detail. Isn't the point of catching the exception to allow me (the programmer) to determine how it should be handled without displaying the exception information? That's what is so puzzling; it handles it in the manner I have chosen, yet goes onto display the exception information. Hmmmmm...

Thanks for any help!

anthutton

I'm still trying to get this all clear in my head. Yes, the idea of a try-catch block is to give you, the programmer, control. If you catch and handle the exceptions correctly, the default error messages wont' show up since you've supposedly "handled" them yourself. Here's how you are handling it, with a default error message. If other error messages are showing up, I imagine that means that you are not handling everything completely. Here's your custom error message:

catch (NumberFormatException nfe) {
                   System.out.println("Scores are not Complete - Please Verify Scores");
			   }

You are printing an error message, but I doubt that will fully handle the problem. There is probably code that is executing that needs to be aborted, or you need to redirect the user to type in input again or something, or you need to exit the program.

So my guess is that you are "handling" it by displaying an exception message, but not handling it fully and aborting code and things are slipping by. Your error message shows, but you still have lousy data. You have a for-loop in there, you may have code afterwords that's executing with bad data that is NOT caught and therefore Java is showing its messages for your UNCAUGHT exceptions. Best bet right now. Exit the program in your catch block code. See if those errors still show up.

Thanks VernonDozier. Yes, exiting works to avoid those errors. However, I want to make it so it does not need to exit, as that would potentially cause the user to lose a lot of work/inputs that were already entered. What you write regarding code that needs to be aborted makes sense, since from these fields the app does a lot of getText statements and it is text inputted that is not numerical that causes the exception in the first place. How do I abort code generally? Does a break statement do the job or can you think of other ways?

Thanks again for all of your help.

anthutton

Here is an example that does not abort, but that ensures that certain code is only executed when valid numbers are entered. It simulates a user entering ten numbers and ensures validity. User (simulated by RNG) enters data is told to try again when invalid data is entered.

import java.util.Random;

public class Main
{
    public static void main(String[] args) 
    {
        String userEntries[] = {"a", "b", "c", "d", "5", "2", "6", "12"};
        int numbers[] = new int[10];
        
        // find ten good numbers
        // randomly assign either good number or bad number as "user input"
        // simulate user input randomly
        Random random = new Random ();
        
        for (int i = 0; i < 10; i++)
        {
            boolean haveGoodNumber = false;
            String userInput = "";

            while (!haveGoodNumber)
            {
                try
                {
                    userInput = userEntries[random.nextInt (userEntries.length)];
                    System.out.println ("User has entered : " + userInput);
                    numbers[i] = Integer.parseInt(userInput);

                    // if bad number, following two lines WILL NOT execute
                    System.out.println ("Catch block bypassed. Valid number has been entered.");
                    haveGoodNumber = true;
                }
                catch (Exception ex)
                {
                    System.out.println ("Invalid number.  Please try again.");
                }
            }
        }

        System.out.println ("Here are the ten numbers");
        for (int i = 0; i < 10; i++)
        {
            System.out.println (numbers[i]);
        }
    }
}

VernonDozier -

I discovered that I actually was attempting to parseInt outside of the try block, and of course when non-numerical data was there, the exception (UNCHECKED, of course since outside the try block!) was created. It's generous of you to offer your time, so thanks again for all of your help!

anthutton

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.