Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In Java, the best way to indicate an exceptional situation is by throwing an exception rather than by returning an error code. Exceptions are propagated across scopes and cannot be ignored in the same way that error codes can. When using exceptions, the error-detection and error-handling code is kept separate from the main flow of control. Also, exceptions can be used in situations where error codes cannot be returned (in constructors, for example).

Noncompliant Code Example

This noncompliant code example attempts to read into an array of characters and to add an extra character into the buffer immediately after the characters read:.

Code Block
bgColor#FFCCCC
static final int MAX = 21;
static final int MAX_READ = MAX - 1;
static final char TERMINATOR = '\\';
int read;
char [] chBuff = new char [MAX];
BufferedReader buffRdr;

// Set up buffRdr

read = buffRdr.read(chBuff, 0, MAX_READ);
chBuff[read] = TERMINATOR;

...

This compliant solution defines a readSafe() method that wraps the original read() method and throws an exception if end-of-file is detected:

Code Block
bgColor#ccccff
public static int readSafe(BufferedReader buffer, char[] cbuf, int off, int len) throws IOException {
  int read = buffer.read(cbuf, off, len);
  if (read == -1) {
     throw new EOFException();
  } else {
     return read;
  }
}

// ...

BufferedReader buffRdr;

// Set up buffRdr

try {
   read = readSafe(buffRdr, chBuff, 0, MAX_READ);
   chBuff[read] = TERMINATOR;
} catch (EOFException eof) {
   chBuff[0] = TERMINATOR;
}

...

Returning an object that might be null on failure or a valid object on success is a common example of in-band error indicator. Although better function designs are often available, returning an object that may be null can be acceptable under some circumstances. See 262. MET54-JG05. Always provide feedback about the resulting value of a method for an example.

...