src/main/java/com/microfocus/application/automation/tools/results/parser/antjunit/AntJUnitReportParserImpl.java
Refactor this code to not throw exceptions in finally blocks. Open
Open
throw new ReportParseException(e);
- Read upRead up
- Exclude checks
Throwing an exception from within a finally block will mask any exception which was previously thrown in the try
or catch
block, and the masked's exception message and stack trace will be lost.
Noncompliant Code Example
try { /* some work which end up throwing an exception */ throw new IllegalArgumentException(); } finally { /* clean up */ throw new RuntimeException(); // Noncompliant; masks the IllegalArgumentException }
Compliant Solution
try { /* some work which end up throwing an exception */ throw new IllegalArgumentException(); } finally { /* clean up */ }
See
- CERT, ERR05-J. - Do not let checked exceptions escape from a finally block
Remove this throw statement from this finally block. Open
Open
throw new ReportParseException(e);
- Read upRead up
- Exclude checks
Using return
, break
, throw
, 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