ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Using Try/Catch Blocks with Java Dialogues

Updated on April 14, 2013

Using Type Casting and the TRY/CATCH Block with Java Swing Dialogues

One of the most important things to remember when you decide to create a user interface is to expect possible user errors that may come up. Indeed, one of the most embarrassing things that could happen in your program is when you ask for user input and they accidentally enter the wrong input type and your program crashes. Yes, it is true that the user made the error, however, as a programmer you must keep this in mind when trying to create you interface.

So, what can you do to make sure this never happens? Well, like all programs, there must be prior planning before you decide that the program is good and try to export it as a usable product. You must consider not only what the interface must look like but how it will handle possible errors. Of course the possibilities are great, however, if you plan out your program prior to writing any code or module, you can possibly catch most of these input errors before you program ever makes it to the market.

In this article, I will create code using dialogues in Java’s Swing class to show you how you can use a generic try/catch block that will allow you to catch a type of input error in which you can correct while the program is running. First, I will show you what I usually do to plan out the specifics of a program by showing you how to use a flow chart and pseudo code. Secondly, this program will also show you how to type cast string input from a Java based dialogue box and change the input to a number in which you can manipulate the number via any type of math algorithm. Third, I will show you how to use a try/catch block to catch user input errors. Last, I will show you the actual JAVA code that I created in NetBeans using the built in JAVA Swing class. Again, as stated earlier, the version of NetBeans I will be using is 7.0.1.

Planning for Possible Errors:

One of the things I like to do is to find out what exactly the user needs from a particular interface. Is it to add numbers or enter text? You have to remember that in pretty much all programming languages there is something known as variable type. When you define a variable or class it is a type (i.e. an int, double, String, etc.). This type must be exact and the only way to make sure user input is the same type is to either catch the error before it is processed or purposely cast the type to fit the correct input.

So, you may have to plan how you will handle this issue by planning accordingly. When I create a plan to handle such issues of a programming language, I usually will fill out a flowchart with some pseudo code (i.e. code that represents more of an English view without actually using a programs code.). In the case of this example, I want to ask the user to input two numbers by way of two dialogue boxes and in return the program will add the two numbers and show a dialogue box with the results. With that said, the following would be the flowchart and pseudo code I would use to help me plan to create the program that catches any incorrect user inputs.

Program FLow Chart

So, by looking at this flowchart, I can plan out the code to catch input errors made by the user and have the program request the correct input. Now the following would be the pseudo code I would use in this situation. Remember, pseudo code is not program specific, it just give you a visual or idea on how you may write the code later within the programming language that you choose.

Program Pseudo-Code

boolean done = false;

While (!done)

String firstNumber = Show Dialogue (input firstNumber);

String secondNumber=Show Dialogue (input seconeNumber);

Try {

Double number1 = cast (firstNumber);

Double number 2 = cast (firstNumber);

Double sum = number1 + number 2;

showMessageDialogue (sum);

done = true;


Catch (numberException)


showDialogue (“You have to Enter Two Numbers”)


Again, the above is only a pseudo code and could be refined to any programming language you wish. Just remember that pseudo code is only a tool to give you an idea how you want the program to flow.

As you can see above, I created a plan that would ask the user to input two numbers via two different dialogue boxes. The try/catch block then takes in the input and determines if the input is correct. If the input is correct, then the two numbers are summed up and the while loop is ended since the Boolean variable “done,” is now set to true. However, if the input where not numbers, the catch block would catch it and produce an error that would ask the user to reenter the number. If it wasn’t for this try/catch block, the program would crash and the user may never know the reason why.

With that said, the following is the code that I ended up with using Java. I am presently using the NetBeans version 7.0.1:

// Author: Bink
// Description: Ask the user to input numbers into 
//              two dialogues and then add the numbers for input 
//              to a third java dialogue.
//              If input is not a number, show the error to the user
package addtiondialogues;
//This program uses JOptionPane
import javax.swing.JOptionPane;
public class AddtionDialogues {
    public static void main(String[] args) {
       boolean done = false;//Control Variable for the while loop
       //repeat until a valid input is entered
           //Obtain user input using two JOption Pane dialogues
           String firstNumber = JOptionPane.showInputDialog("Enter first integer");
           if(firstNumber == null || firstNumber.length() == 0) {
               firstNumber = "0";
           String secondNumber = JOptionPane.showInputDialog("Enter second integer");
           if(secondNumber == null || secondNumber.length() == 0) {
               secondNumber = "0";

            //convert String input to int values to use in a calculation
            //Catch an error if input was not a number
            double number1 = Double.parseDouble(firstNumber);//change to double
            double number2 = Double.parseDouble(secondNumber);//change to double
            //Add input values (number1 + number2) to sum variable
            double sum = number1 + number2;
            //Show results in a new JOptionPane dialogue
            JOptionPane.showMessageDialog(null, "The sum is " + sum,
                    "Sum of Two Integers",JOptionPane.PLAIN_MESSAGE);
            //exit while loop
            done = true;
            } //Catch error if input was not a number and repeat while loop.
            catch ( NumberFormatException e){
                        "Error: You have to enter two numbers!",
                        "Error Message",JOptionPane.ERROR_MESSAGE);
                }//end try/catch block       
       }//end while loop
    }//end main
}//end AdditionDialogues Class

So, now I will explain the code above to give you an idea what is going on. First, I created a new project with the package name of “additional dialogues,” with a public class name of “Additional Dialogues.” I also imported the built Java class “javax.swing.JOptionPlane.” This imported class will allow you create dialogues for input.

Within the Additional Dialogue class you have the main function. This function is the entry point to your program. Next I set up a Boolean variable “done,” which will be the variable that controls your while loop. If the user enters the numbers correctly, then this Boolean variable will change to true and the loop will be exited.

Next, we have the while loop. As stated above, the wile loop will continuously run until the correct input is entered. Since the variable “done,” is set to false, then the symbol “!” is used to tell the while loop that until this variable is true, continue looping.

The next variables will hold the input string that the user enters and will initialize two individual dialogue boxes to get that input. When you use dialogue boxes, the input that the user enters will be of a string value. This also goes for numbers as well.

The next section of code is the try/catch block. This is where the decision is made to determine if the user did indeed actually enter integers and not other type of characters. Within the try block I created two new double type variables (double type variables allow you to use decimal variables). These two variables will be use to add the two numbers inputted by the user. You may also noticed that both variables use a parsing statement (i.e. number1 = Double.parseDouble (firstNumber)). This is called type casting. Remember that the type that the user inputs within the dialogue box is a string; however, you cannot use any type of math algorithm with strings, only numbers. So, user input has to be what programmers call “type casted,” to make sure that any math on inputted numbers can be done. Finally, within this block, the numbers are added and returned to the user via a dialogue box and the loop variable of done is set to true to end the loop.

However, if within the try block, the input from the user was not a number, then the catch block is ran and the user is asked to enter the correct input. So, the program will continue to run until the user finally inputs the correct information. With that said, the following graphics shows and example of what happens when you finally run this program:

Figure 1: User enters random character

Figure 2: User enters a letter as input.

Figure 3: Program produces an error and user is asked to re-input intergers

Figure 4: User re-inputs first integer.

Figure 5: User inputs second integer.

Figure 6: Program returns correct result to user.

Final Conclusion

In this example, I showed you how to create a simple version of a graphic user interface in which the user can enter input. I also showed how to use type casting in java as well as how to use a try/catch block to catch any errors and in turn to keep the program from crashing. However, this program is still not crash proof. There is one problem with this program that I did not cover as it pertains to user input. I decided to leave it up to you to decide what that problem is. However, I will give you a hint: The cancel button on the dialogue buttons could cause your program to crash. Again, I will leave it up to you to figure out how to compensate for this problem and figure out how to change the program to catch this error. Happy coding!!!!

Great Programming Books from Amazon

Please enter any comments here.

    0 of 8192 characters used
    Post Comment

    • profile image

      Brandon 4 years ago

      what will happen when u cancel the option it will crash id-10t

    • Binkster profile image

      Binkster 4 years ago

      Hey Brandon,

      Yes, the program will crash if you press the cancel button on one or both of the dialogues. There is a simple fix to this problem. When you create the new variables firstNumber and secondNumber, you will also need two additional if statements to see if these variables are "null", if so you can manually assign them an initial string. In this case, I would use "0". The above code has been updated with the new if statements. If you run the program now and press the cancel buttons, the program will not crash and give you a final value of 0.0.

      Hope this helps to answer your question.


    Click to Rate This Article