
Exceptions should be used only to denote exceptional conditions. They should not be used for ordinary control flow purposes, for several reasons. First, catching an exception is likely to catch unexpected errors; see ERR08-J. Do not catch NullPointerException or any of its ancestors for examples. When a program catches a specific type of exception, it does not know exactly where that exception was thrown. Using a catch clause to handle an exception that occurs in a known location is a poor solution; it is preferable to handle the error as soon as it occurs, or prevent it, if possible. The non-locality of throw statements and corresponding catch statements can also impede optimizers from improving code that relies on exception handling. Catching exceptions also complicates debugging, as they indicate a jump in control flow from the throw statement to the catch clause. Finally, exceptions need not be implemented to perform optimally, as it is assumed they are only thrown upon exceptional circumstances. Throwing and catching an exception will often yield slower code than handling the error with some other mechanism.
Noncompliant Code Example
This noncompliant code example attempts to concatenate the string elements of the array values
, storing the result as the first element:
String values[] = new String[3]; values[0] = "value1"; values[1] = "value2"; values[2] = "value3"; int i; values[1] = null; // Gets null value try { i = 0; while(true) { values[0] = values[0].concat(values[i + 1]); // Concatenate and store in values[0] i++; } } catch (ArrayIndexOutOfBoundsException e) { i = 0; // Attempts to initialize i to 0 } catch (NullPointerException npe) { // Ignores }
It uses an ArrayIndexOutOfBoundsException
to detect the end of the array and reinitialize the value of variable i
to 0
in the catch
block. However, when some element of the array is null
, a NullPointerException
results. This exception is caught and ignored, a violation of ERR08-J. Do not catch NullPointerException or any of its ancestors. Consequently, the variable i
fails to be reinitialized.
Compliant Solution
This compliant solution uses a standard for
loop to concatenate the strings:
String values[] = new String[3]; values[0] = "value1"; values[1] = "value2"; values[2] = "value3"; int i; for (i = 1; i < values.length; i++) { values[0] = values[0].concat(values[i]); } i = 0; // Initialize i to 0 after operation
Applicability
Use of exceptions for any purpose other than detecting and handling exceptional conditions complicates program analysis and debugging, degrades performance and can increase maintenance costs.
Bibliography
[Bloch 2001] | Item 39, "Use Exceptions Only for Exceptional Conditions" |
[JLS 2011] | Chapter 11, "Exceptions" |