Software Engineering
Home Planning Requirements Writing Hazard Analysis Requirement Analysis Config Control Software Design Software Testing Software Standards Basic Logic

Software Design - Don't Try - DO!

Misuses of try...catch

An exception is simply an error that can occur without any component failure or software defect. For example, a printer can reasonably be expected to run out of paper from time to time; therefore, a "printer out of paper" error is an exception.

C++ provides a try...catch mechanism for exception handling. Try...catch is fine for errors that do not allow a function's operation to continue, such as memory exceptions. It's primary advantage is the stack unwinding when jumping out of nested functions. Unfortunately, try...catch is often mis-used, as it was in the true story about the floppy disk error ===>>

Consider the original file save logic in pseudo-code:

Original Code:
   SaveFile(filename);

After testing, the developer added the following:
   try{
     SaveFile(filename);
   {
   catch {
     SaveFile(filename);
   }

A better method would be to think about exception handling in the beginning and use the following logic:

  DO {
    ok = SaveFile(filename);
    if (NOT ok) {
      Prompt User to Retry or Abort
      if (Abort) ok = TRUE
    }
  WHILE (NOT ok)

The above logic will continually attempt to save the file until it either succeeds or the user aborts.

Don't Try - DO!

True Horror Story

On a software project, a senior programmer wrote a function to save a file to disk, allowing the user to select the directory.

Our software testing group just *loved* to try and break anything we wrote! So they selected the A: drive and tried to save without a floppy disk in the drive. The program threw an unhandled exception and terminated!

The developer had not thought about this scenario, and had not included any error handling if a write operation failed.

The developer's solution was to simply encase the entire function in a try...catch block. In the catch block, the function call was repeated, giving the person a second chance to save the file.

This certainly used the minimum code, but when it got back to testing, the testers decided to see what happened if they *never* put a disk in the floppy drive and just kept re-trying. The catch block caught the first failure, but the second failure resulted in another unhandled exception!

Or, to paraphrase one of my favorite lines from the original movie Dune:

"The Program tried and failed?"
"It tried and died!"