Rule Definition
Exception handling tends to be relatively costly, given the work in unwinding the stack, trying various exception handlers, and so on. You should avoid placing try/catch blocks within a method that is called in a loop as it can add up when performed many times inside a loop.
Remediation
If possible, put the loop inside the try/catch block.
Violation Code Sample
public class ExceptionTest {
static final int N = 18000000;
public void myException(void) {
Throwable exc = new Throwable();
try {
throw exc;
} catch (Throwable e) { }
}
}
public class LoopTest {
static final int N = 18000000;
private ExceptionTest et = new ExceptionTest();
public void myLoop(void) {
for (int i = 1; i <= N; i++) {
et.myException(); // VIOLATION
}
}
}
Fixed Code Sample
public class ExceptionTest {
static final int N = 18000000;
public void myException(void) throws Throwable {
Throwable exc = new Throwable();
throw exc;
}
}
public class LoopTest {
static final int N = 18000000;
private ExceptionTest et = new ExceptionTest();
public void myLoop(void) {
try {
for (int i = 1; i <= N; i++) {
et.myException(); // FIXED
}
} catch (Throwable e) { }
}
}
Reference
http://www.precisejava.com/javaperf/j2se/Exceptions.htm
Related Technologies
Technical Criterion
Efficiency - Expensive Calls in Loops
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.