
org.sonar.l10n.java.rules.squid.S1143.html Maven / Gradle / Ivy
return
ing, break
ing, throw
ing, and so on from a finally
block suppresses the propagation of any unhandled Throwable
which was thrown in the try
or catch
block.
This rule raises an issue when a jump statement (break
, continue
, return
, throw
, and goto
) would force control flow to leave a finally
block.
Noncompliant Code Example
public static void main(String[] args) {
try {
doSomethingWhichThrowsException();
System.out.println("OK"); // incorrect "OK" message is printed
} catch (RuntimeException e) {
System.out.println("ERROR"); // this message is not shown
}
}
public static void doSomethingWhichThrowsException() {
try {
throw new RuntimeException();
} finally {
for (int i = 0; i < 10; i ++) {
//...
if (q == i) {
break; // ignored
}
}
/* ... */
return; // Noncompliant - prevents the RuntimeException from being propagated
}
}
Compliant Solution
public static void main(String[] args) {
try {
doSomethingWhichThrowsException();
System.out.println("OK");
} catch (RuntimeException e) {
System.out.println("ERROR"); // "ERROR" is printed as expected
}
}
public static void doSomethingWhichThrowsException() {
try {
throw new RuntimeException();
} finally {
for (int i = 0; i < 10; i ++) {
//...
if (q == i) {
break; // ignored
}
}
/* ... */
}
}
See
- MITRE, CWE-584 - Return Inside Finally Block
- CERT, ERR04-J. - Do not complete abruptly from a finally block
© 2015 - 2025 Weber Informatics LLC | Privacy Policy