Try/Catch Block In Loop
ID |
java.loop_try_in_loop |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
efficiency |
Rationale
Setting up a try/catch frame on every loop iteration adds runtime overhead. When the exception-handling logic is the same for all iterations, hoisting the try/catch outside the loop avoids the repeated setup cost without changing the program’s semantics.
// Bad - try inside loop
for (int i = 0; i < 10; i++) {
try {
riskyOperation(i);
} catch (Exception e) {
log(e);
}
}
Remediation
Move the try/catch block outside the loop.
// Good - try outside loop
try {
for (int i = 0; i < 10; i++) {
riskyOperation(i);
}
} catch (Exception e) {
log(e);
}