Java Try Catch Finally blocks without Catch

后端 未结 11 789
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 20:38

I\'m reviewing some new code. The program has a try and a finally block only. Since the catch block is excluded, how does the try block work if it encounters an exception

11条回答
  •  时光取名叫无心
    2020-11-28 21:04

    The inner finally is executed prior to throwing the exception to the outer block.

    public class TryCatchFinally {
    
      public static void main(String[] args) throws Exception {
    
        try{
            System.out.println('A');
            try{
                System.out.println('B');
                throw new Exception("threw exception in B");
            }
            finally
            {
                System.out.println('X');
            }
            //any code here in the first try block 
            //is unreachable if an exception occurs in the second try block
        }
        catch(Exception e)
        {
            System.out.println('Y');
        }
        finally
        {
            System.out.println('Z');
        }
      }
    }
    

    Results in

    A
    B
    X
    Y
    Z
    

提交回复
热议问题