org.sonar.l10n.javascript.rules.javascript.S1143.html Maven / Gradle / Ivy
The purpose of a finally
block is to ensure the cleanup of objects (e.g. closing the file), it is executed after try
and
catch
blocks under any circumstances. Having a return
or a thrown exception in a finally
block suppresses the
propagation of any unhandled exception which was thrown in the try
or catch
block or overwrite the returned value.
This rule will report on all usages of jump statements (return
, break
, throw
, and continue
)
from a finally
block. Even if it’s guaranteed that no unhandled exception can happen in try
or catch
blocks,
it’s not recommended to use any jump statements inside the finally
to have the logic there limited to the "cleanup".
Noncompliant Code Example
async function foo() {
let result, connection;
try {
connection = await connect();
result = connection.send(1);
} catch(err) {
console.error(err.message); // if this line throws, this exception will not be propagated
} finally {
connection.close();
return result; // Noncompliant
}
}
Compliant Solution
async function foo() {
let result, connection;
try {
connection = await connect();
result = connection.send(1);
} catch(err) {
console.error(err.message);
} finally {
connection.close();
}
return result;
}
See
- MITRE, CWE-584 - Return Inside Finally Block