编程语言
首页 > 编程语言> > java – JVM如何执行Try catch finally块

java – JVM如何执行Try catch finally块

作者:互联网

根据Java语言规范,Section §14.20.2

A try statement with a finally block is executed by first executing the try block. Then there is a choice:

  • If execution of the try block completes normally, then the finally
    block is executed, and then there is a choice:

解决方法:

经过一点点搜索并看到生成了什么字节码后,我发现实际上没有看起来没有finally块,也没有JVM生成的跳转或goto语句.
上面的代码被翻译为(如果我正确解释字节代码,如果我错了请请纠正我)

public static int TestTryFinallyBlock()  
{
  int returnValue; //A temporary return variable
  try
  {
     int  i = 0;     
     i = 10; 
     returnValue = i; 
     i = 40; 
     return returnValue;    
  }
  catch (RuntimeException e)
  {
       i = 40; //finally section code id copied here too
       throw e;
  }
}

注意:如果’i’是对可变类对象的引用,并且在finally块中更改了对象的内容,那么这些更改也会反映在返回的值中.

标签:try-finally,java
来源: https://codeday.me/bug/20190728/1565167.html