Java Reference
In-Depth Information
// Report the abnormal/error condition here
}
else {
// Perform division here
z = x/y;
}
You may observe that this snippet of code does two things: it handles the error condition and performs the
intended action. It mixes the code for performing error handling and the action. One line of code ( z = x/y ) has
bloated to at least five lines of code. This is a simple example. You may not fully realize the real problem when the
error handling code is mixed with the actual code performing actions.
To make this problem clear, let's consider another example. Suppose you want to write Java code that will update
an employee's salary. An employee's records are stored in a database. The pseudocode might look as follows:
Connect to the database
Fetch the employee record
Update the employee salary
Commit the changes
The actual code would perform the above-mentioned four actions. Any of the four actions may result in an
error. For example, you may not be able to connect to the database because the database is down; you may not be
able to commit the changes because of some validations failed. You need to perform error checking after an action is
performed and before the subsequent action is started. The pseudocode with error checking may look as follows:
// Connect to the database
if (connected to the database successfully) {
// Fetch the employee record
if (employee record fetched) {
// Update the employee salary
if (update is successful) {
// Commit the changes
if (commit was successful ) {
// Employee salary was saved successfully
}
else {
// An error. Save failed
}
}
else {
//An error. Salary could not be updated
}
}
else {
// An error. Employee record does not exist
}
}
else {
// An error. Could not connect to the database
}
 
Search WWH ::




Custom Search