Error Value

An alternative to throwing exceptions.

Rather than:

 try { doSomething(); } catch (SomeException e) { handleException(e); }
We might have:
 boolean success = doSomething();  if (!success) handleException(e);
The above would need some magic to get at the exception information e. So we might have to use:

 ReturnCode rc = doSomething();  if (rc != SUCCESS) handleException(rc);
But see UseExceptionsInsteadOfErrorValues.


ExceptionHandlingChallenge entry 1: Use ErrorValues and if (success)

Newkirk and Martin used the following code (ExtremeProgrammingInPractice, p120):

 boolean success = UserDatabase.add(user);
 if (success) {
 if (mailPassword(email, password))
 redirect("success");
 else {
 UserDatabase.delete(email); //this can fail also !!!
 redirect("mailfailure");
 }
 } else {
 redirect("addfailure");
 }

Pros: Cons:


ExceptionHandlingChallenge entry 2: Use ErrorValues and if (!success)

A variation on the above:

 boolean successWhenAdding = UserDatabase.add(user);
 if (!successWhenAdding)
 redirect("addfailure");

boolean successWhenMailing = mailPassword(email, password)); if (!successWhenMailing) { UserDatabase.delete(email); //this can also fail !!! redirect("mailfailure"); }

redirect("success");

Pros: Cons: Giving...
 boolean successWhenAdding = UserDatabase.add(user);
 if (!successWhenAdding) {
   redirect("addfailure");
   return false;
 }

boolean successWhenMailing = mailPassword(email, password)); if (!successWhenMailing) { UserDatabase.delete(email); //this can also fail !!! redirect("mailfailure"); return false; }

redirect("success"); return true;
or...
 boolean success = UserDatabase.add(user);
 if (!success)
   redirect("addfailure");

if (success) { success = mailPassword(email, password)); if (!success) { UserDatabase.delete(email); //this can also fail !!! redirect("mailfailure"); } }

if (success) redirect("success");

return success;
or, if you want symmetry...
 boolean success = true;

if (success) { UserDatabase.add(user); if (!success) redirect("addfailure"); } // etc...


Some suggest error values are problematic because "true" functions only return one value. Thus, errors allegedly "waste" the return value for other uses. Here are two ways to get around this. The first is to return an array/structure/object:

  resultArray = doSomething(...)
  if (!resultArray.good) ...

Another is to specify the result variable as a parameter:

  doSomething(param1, param2, errorVar="status")
  if (!status) ...

If the error variable is not requested, then the routine does its own error handling (such as a message and stop). This is why it is an optional parameter. This works better for some languages than others.


CategoryException


EditText of this page (last edited April 1, 2005) or FindPage with title or text search