Why this matters
Using control flow statements inside finally blocks suppresses exceptions and can lead to unexpected behavior.
return, break, or continue in finally BlocksDo not use return, break, or continue inside finally blocks as they can suppress exceptions and lead to unintended behavior.
Using control flow statements inside finally blocks suppresses exceptions and can lead to unexpected behavior.
Side-by-side examples engineers can pattern-match during review.
class ReturnInFinally {
int nonCompliantMethod(int n) {
for (int i = 0; i < n; ++i) {
try {
functionThrowingException(i);
} catch (e) {
print(e);
} finally {
return 1; // Noncompliant
}
}
return 0;
}
}class Ok {
int nonCompliantMethod(int n) {
for (int i = 0; i < n; ++i) {
try {
functionThrowingException(i);
} catch (e) {
print(e);
return 1;
}
}
return 0;
}
}From the same buckets as this rule.
Check if loops use equality operators (== or !=) in termination conditions. These can lead to infinite loops if the condition is never met exactly. Instead, use relational operators like < or > for safer loop termination.