Java Reference
In-Depth Information
nore values returned by methods,” but also has the unfortunate effect of propagating in-
valid values that may subsequently be treated as valid in later computations.
Avoid the use of in-band error indicators. They are much less common in Java's core
library than in some other programming languages; nevertheless, they are used in the
read(byte[] b, int off, int len) and read(char[] cbuf, int off, int len)
families of methods in java.io .
In Java, the best way to indicate an exceptional situation is by throwing an exception
ratherthanbyreturninganerrorcode.Exceptionsarepropagatedacrossscopesandcannot
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.
Click here to view code image
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;
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 ArrayIn-
dexOutOfBoundsException .
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:
Click here to view code image
Search WWH ::




Custom Search