Monday 1 May 2017

Return statements should not occur in finally blocks


Prevents the RuntimeException from being propagated.

Returning from a finally block suppresses the propagation of any unhandled Throwable which was thrown in the try or catch block.

public static void main(String[] args) {
  try {
    doSomethingWhichThrowsException();
    System.out.println("OK");
  } catch (RuntimeException e) {
    System.out.println("ERROR");
  }                                                      
}

public static void doSomethingWhichThrowsException() {
  try {
    throw new RuntimeException();
  } finally {
    /* ... */
    return;   // Non-Compliant - prevents the RuntimeException from being propagated
  }
}


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...