Using return
, break
, or continue
from a finally
block suppresses the propagation of any
unhandled Exception
which was thrown in the try
or catch
block.
This rule raises an issue when a jump statement (break
, continue
, return
) would force control flow to leave
a finally
block.
Noncompliant code example
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 ContinueInFinally {
int nonCompliantMethod(int n) {
for (int i = 0; i < n; ++i) {
try {
functionThrowingException(i);
} catch (e) {
print(e);
} finally {
continue; // Noncompliant
}
}
return 0;
}
}
class BreakInFinally {
int nonCompliantMethod(int n) {
for (int i = 0; i < n; ++i) {
try {
functionThrowingException(i);
} catch (e) {
print(e);
} finally {
break; // Noncompliant
}
}
return 0;
}
}
Compliant solution
class Ok {
int nonCompliantMethod(int n) {
for (int i = 0; i < n; ++i) {
try {
functionThrowingException(i);
} catch (e) {
print(e);
return 1;
}
}
return 0;
}
}