21.08.2013 Views

Software Engineering for Students A Programming Approach

Software Engineering for Students A Programming Approach

Software Engineering for Students A Programming Approach

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

246 Chapter 17 ■ <strong>Software</strong> robustness<br />

><br />

><br />

public void actionPer<strong>for</strong>med(ActionEvent event) {<br />

String string = ageField.getText();<br />

age = Integer.parseInt(string);<br />

if (age > 18)<br />

response.setText("you can vote");<br />

else<br />

response.setText("you cannot vote");<br />

}<br />

This piece of program, as written, provides no exception handling. It assumes that<br />

nothing will go wrong. So if the user enters something that is not a valid integer,<br />

method parseInt will fail. In this eventuality, the program needs to display an error<br />

message and solicit new data, (see Figure 17.2).<br />

To the programmer, checking <strong>for</strong> erroneous data is additional work, a nuisance, that<br />

detracts from the central purpose of the program. For the user of the program, however,<br />

it is important that the program carries out vigilant checking of the data and when<br />

appropriate displays an in<strong>for</strong>mative error message and clear instructions as to how to<br />

proceed. What exception handling allows the programmer to do is to show clearly what<br />

is normal processing and what is exceptional processing.<br />

Here is the same piece of program, but now written using exception handling. In<br />

the terminology of exception handling, the program first makes a try to carry out some<br />

action. If something goes wrong, an exception is thrown by a piece of program that<br />

detects an error. Next the program catches the exception and deals with it.<br />

public void actionPer<strong>for</strong>med(ActionEvent event) {<br />

String string = ageField.getText();<br />

try {<br />

age = Integer.parseInt(string);<br />

}<br />

catch (NumberFormatException e){<br />

response.setText("error. Please re-enter number");<br />

return;<br />

}<br />

if (age > 18)<br />

response.setText("you can vote");<br />

else<br />

response.setText("you cannot vote");<br />

}<br />

In the example, the program carries out a try operation, enclosing the section of program<br />

that is being attempted. Should the method parseInt detect an error, it throws<br />

a NumberFormatException exception. When this happens, the section of program<br />

enclosed by the catch keyword is executed. As shown, this displays an error message<br />

to the user of the program.<br />

><br />

>

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!