Java Reference
In-Depth Information
Exceptions
Java exception processing has the reputation of being expensive. It is somewhat more ex-
pensive than processing regular control flows, though in most cases, the extra cost isn't
worth the effort to attempt to bypass it. On the other hand, because it isn't free, exception
processing shouldn't be used as a general mechanism either. The guideline here is to use ex-
ceptions according to the general principles of good program design: mainly, code should
only throw an exception to indicate something unexpected has happened. Following good
code design means that your Java code will not be slowed down by exception processing.
Two things can affect the general performance of exception processing. First, there is the
code block itself: is it expensive to set up a try-catch block? While that might have been the
case a very long time ago, it has not been the case for years. Still, because the Internet has a
long memory, you will sometimes see recommendations to avoid exceptions simply because
of the try-catch block. Those recommendations are out of date; modern JVMs can generate
code that handles exceptions quite efficiently.
The second aspect is that (most) exceptions involve obtaining a stack trace at the point of the
exception. This operation can be expensive, particularly if the stack trace is deep.
Let's look at an example. Here are three implementations of a particular method to consider:
public
public ArrayList < String > testSystemException () {
ArrayList < String > al = new
new ArrayList <>();
for
for ( int
int i = 0 ; i < numTestLoops ; i ++) {
Object o = null
null ;
iif (( i % exceptionFactor ) != 0 ) {
o = new
new Object ();
}
try
try {
al . add ( o . toString ());
} catch
catch ( NullPointerException npe ) {
// Continue to get next string
}
}
return
return al ;
}
public
public ArrayList < String > testCodeException () {
ArrayList < String > al = new
new ArrayList <>();
for
for ( int
int i = 0 ; i < numTestLoops ; i ++) {
try
try {
iif (( i % exceptionFactor ) == 0 ) {
Search WWH ::




Custom Search