关于finally的生效范围

一直以为finally是在一个try-catch块中,不管里面有没抛异常,
最终都会去执行的一个块,比如
public void testFinallyMethod(){
  try{
     System.out.println(">>>do something<<<");
     System.out.println(">>>do other thing<<<");
  }catch (Exception e){

  }finally{
     System.out.println(">>>always do something<<<");
  }
}


然而今天同事有个需求,就是在try块中return/break/continue
那么finally块是否会继续执行呢?
答案是肯定的.
public void testFinallyMethod(){
  try{
     System.out.println(">>>do something<<<");
     return;//break,continue 也一样,当然这2种需要在循环中
     System.out.println(">>>do other thing<<<");
  }catch (Exception e){

  }finally{
     System.out.println(">>>always do something<<<");
  }
}

运行后的结果是
>>>do something<<<
>>>always do something<<<

你可能感兴趣的:(java)