Java Reference
In-Depth Information
1.
In the c7.EnterEmpInfo actionPerformed method, select the statement that parses
empPayRate, click Source , Surround With , then Try/catch Block .
The resulting code will be:
try {
doubleEmpPR = Double. parseDouble (empPayRate);
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Notice that RAD knew which exception(s) could be thrown and inserted the correct catch block(s). However,
putting the parseDouble statement into the try block caused new errors. The JVM is smart enough to know that
a statement in a try block may not be executed (because of an exception). If the parseDouble statement is never
executed, no value will be assigned to doubleEmpPR. Therefore, statements that use doubleEmpPR are flagged with
an error.
To avoid this error, we will initialize the variable to negative one. (Later in the application we determine if we
should continue processing by checking if the pay rate value is still -1 or not.)
2.
In actionPerformed, change the variable's definition statement to the following:
double doubleEmpPR = -1, doubleGross;
3.
Change the catch block to the following:
catch (NumberFormatException error) {
empPRTF.setText("");
resultLbl.setForeground(Color.red);
resultLbl.setText("Pay rate must be a numeric " +
"value: 1, 2, 3...");
}
The first statement clears the invalid value in the empPRTF field. This makes it harder for the user to reenter the
incorrect value. The second statement changes the result label's text color to red (so that the message will be more
noticeable and because red is the universal color for errors), but notice that the statement has an error. The value red
that was specified is not just simple text. It is actually a variable stored in the class Color . Because of this, we must
include an import statement for the class Color .
4.
Click on the text Color so the insertion point is in the text.
5.
Press and hold the Ctrl and Shift keys, and then press the M key.
After clicking on a class name, Ctrl-Shift-M is a RAD shortcut for adding the correct import statement. In this
case, import java.awt.Color; is added. (If there are classes with the same name in different packages, a window will
be displayed with the available options to select from.)
Finally, notice that the third statement in the catch block displays a “matter of fact” message that identifies
the field that had the incorrect value and provides examples of valid values. Most organizations will have their own
standards for error messages (i.e., their color, content, etc.) and these standards could dictate much more elaborate
messages. For instance, an error message could include instructions for resolving the error, provide a contact person
for help, contain a hyperlink to more detailed error information, etc. However, this is an example of a good simple
error message.
Search WWH ::




Custom Search