Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

will the nested try exception be caught by outer catch block

I have something like this

try{   
  try{ . .a method call throwing a exception..} 
  finally { ...} 
} catch()...

The type of exception thrown by method call and outer catch(type parameter) is same.

Will the nested try exception be caught by outer catch block?

like image 354
curious Avatar asked Dec 11 '22 22:12

curious


1 Answers

The relevant rules are in the Java Language Specification, 14.20.2. Execution of try-finally and try-catch-finally

The result of an exception V in the inner try block will depend on how the finally block completes. If it completes normally, the try-finally will complete abruptly due to V. If the finally block completes abruptly for some reason R then the try-finally completes abruptly due to R, and V is discarded.

Here is a program demonstrating this:

public class Test {
  public static void main(String[] args) {
    try {
      try {
        throw new Exception("First exception");
      } finally {
        System.out.println("Normal completion finally block");
      }
    } catch (Exception e) {
      System.out.println("In first outer catch, catching " + e);
    }
    try {
      try {
        throw new Exception("Second exception");
      } finally {
        System.out.println("finally block with exception");
        throw new Exception("Third exception");
      }
    } catch (Exception e) {
      System.out.println("In second outer catch, catching " + e);
    }
  }
}

Output:

Normal completion finally block
In first outer catch, catching java.lang.Exception: First exception
finally block with exception
In second outer catch, catching java.lang.Exception: Third exception

The second outer catch did not see "Second exception" because of the abrupt completion of the second finally block.

Try to minimize the risk of abrupt completion of the finally block. Handle any exceptions inside it, so that it will complete normally, unless they are going to be fatal to the program as a whole.

like image 89
Patricia Shanahan Avatar answered Dec 28 '22 08:12

Patricia Shanahan