...
- A valid object or a null reference.
- An integer indicating a positive value, or −1 to indicate that an error occurred.
- An array of valid objects or a null reference indicating the absence of valid objects. (This topic is further addressed in 41 MET55-J. Return an empty array or collection instead of a null value for methods that return an array or collection)
In-band error indicators require checking for the error; however, this checking is often overlooked. Failure to check for such error conditions not only violates EXP00-J. Do not ignore values returned by methods but also has the unfortunate effect of propagating invalid values that may subsequently be treated as valid in later computations.
...
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 as easily as error codes can. When using exceptions, the error-detection and error-handling code is kept separate from the main flow of control.
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 that are read.
...
However, if the input buffer is initially at end-of-file, the read
method will return −1, and the attempt to place the terminator character will throw an ArrayIndexOutOfBoundsException
.
Compliant Solution (Wrapping)
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 | ||
---|---|---|
| ||
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; } |
Applicability
Using in-band error indicators may result in programmers either failing to check status codes or using incorrect return values, leading to unexpected behavior.
...
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 method designs are often available, returning an object that may be null can be acceptable under some circumstances. See 26 MET54-J. Always provide feedback about the resulting value of a method for an example.
Bibliography
...