Home Segments Top Top Previous Next

937: Practice

The form definition provided in Segment 930 has one conspicuous defect from the defensive programming point of view: A user can type in the text fields something other than an integer and thus can wreak havoc.

To protect against such disasters, replace the direct calls to the setters in the local listener with calls to private setters that take string arguments. In those new private setters, check to see whether the strings are integers by trying to interpret them as integers, and catching a NumberFormatException if you fail. Then, if you succeed, call the regular integer-argument setter on the resulting interpretation; otherwise, if you fail, call the regular integer-argument setter with the current value.