Working with JFC/Swing Controls using NetBeans IDE - Introducing error handling or exception handling in Java using NetBeans IDE: explanation
(Page 6 of 6 )
From the above sections, everybody knows that the following statement simply converts the value available in "txtFirst" to an integer and assigns the same to the variable "a."
a = Integer.parseInt(this.txtFirst.getText());
If the user tries to provide an invalid value (or even a blank value), our program tends to crash. To solve this problem, I modified the above line with proper exception handling as follows:
//check for the validity of first number
try
{
a = Integer.parseInt(this.txtFirst.getText());
}
catch(Exception e)
{
this.txtFirst.setBackground(java.awt.Color.RED);
this.txtFirst.requestFocus();
return;
}
Even though the above code fragment looks a bit complicated, it is very simple to understand. When it tries to execute the following statement:
a = Integer.parseInt(this.txtFirst.getText());
it checks to see whether any runtime error occurred. If no error occurred, it proceeds to the statement which is next to the "catch" block. If any error occurs, it executes the following statements available in the "catch" block.
this.txtFirst.setBackground(java.awt.Color.RED);
this.txtFirst.requestFocus();
return;
The above statements would simply change the background color to RED and take the cursor to that control. We have something similar set up for the variable "b" also. If the execution passes without any errors, it executes the following statements.
//set back the colors and give the result
this.txtFirst.setBackground(java.awt.Color.WHITE);
this.txtSecond.setBackground(java.awt.Color.WHITE);
this.lblResult.setText(String.valueOf(a+b));
Any doubts, bugs, errors, suggestions, feedback etc. are highly appreciated at jag_chat@yahoo.com.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |