try catch finally解惑

try catch finally解惑

Finally通常会配合try、catch使用,在try。。。catch没有退出的语句(return 或者是抛出异常导致退出try。。。catch)执行完try。。。catch语句后,再来执行finally;另外一种情况是在try。。。catch有退出的语句,在每一处的try或catch将要退出该方法之前,JVM都会保证先去调用finally的代码,这里所说的退出不单单是指return语句,try或catch中异常的抛出也会导致相应方法的退出(当然,前提是不被catch捕获以及不被finally跳转)。在执行finally代码时,如果finally代码本身没有退出的语句(return或抛出异常),finally执行完毕(除了finally中有return语句)后还会返回try或catch之前要退出的地方,由try或catch执行退出指令。

static intf4() { 

            try

                throw new Exception("try error "); 

            } catch (Exception e) { 

               System.out.print("throw excetion ");

                throw new RuntimeException("catch error "); 

            } finally

                System.out.print("f4"); 

                Return 0

            } 

结果:throw excetion f4 : 0

在通过外面的程序调用这个函数

try

            System.out.println(" : " + f4()); 

        } catch (Exception e) { 

            System.out.println(" : " + e.getMessage()); 

  } 

在上面程序中先抛出throw new Exception("try error"异常,同时被catch到然后执行

System.out.print("throw excetion");

当执行到throw new RuntimeException("catcherror");  时,编译器知道这是退出的意识(还包括return 语句等),此时由于finally具有在try或catch将要退出(包括return 以及抛出异常)该方法之前,JVM都会保证先去调用finally的代码,此时执行finally中的代码

System.out.print("f4"); 

Return 0

此时该函数f4()并没有向外抛射异常

同样的道理

static int f4() { 

            try

                throw new Exception("try error "); 

            } catch (Exception e) { 

             System.out.print("throw excetion ");

                 return 1;

            } finally

                System.out.print("f4"); 

                return 0;

            } 

         

       } 

此时结果

throwexcetion f4 : 0

static int f4() { 

            try

             System.out.print("try ");

                 return 2;

            } catch (Exception e) { 

             System.out.print("throw excetion ");

                 return 1;

            } finally

                System.out.print("f4"); 

                return 0;

            }  

         

       } 

结果try f4 : 0

还有就是执行完try。。。catch(此时没有退出的语句)在执行完try。。。catch的语句后,再来执行finally如:

static int f4() { 

            try

             System.out.print("try ");

               

            } catch (Exception e) { 

             System.out.print("throw excetion ");

               

            } finally

                System.out.print("f4"); 

                return 0;

            } 

         

       } 

结果try f4 : 0

猜你喜欢

转载自blog.csdn.net/liu891208/article/details/45289585