Java bytecode analysis - try catch finally

ydfind 2022-05-22 12:18:37 阅读数:972


java Bytecode analysis -try catch finally


1.try Inside "return x;" Will x Save to local variable table x The location of , It's equivalent to making a copy of x, Write it down as xx. if finally Are there in return sentence , Will perform finally Inside return; otherwise , Will xx(finally It can be modified x Value , But it can't be modified xx Value , if xx Is quoted , such as map, You can use the x Revised xx What's in it ) Take it out and return .
2.try Error report in execution , Jump to the catch,catch Of return and finally Of return The analysis is as above , Priority return finally Of return;
3. When catch Something unusual happened in the , Will also run finally Code block ;
4. In bytecode finally Code blocks appear many times ;

make a concrete analysis

public static int test3() {
int a = 1;
try {
return a / 0;
} catch (Exception e) {
return a + 2;
} finally {
return a + 3;

 Insert picture description here
Code block [2,5] The execution error will run to catch The beginning of 10, Not Exception If you report an error, go to finally The beginning of 19.
catch Code block for [10,14] If something goes wrong, it will run to finally At the beginning 19.
 Insert picture description here
You can see that the bytecode is like this :

try Code block
finally Code block 1 -> try No code error , The normal exit
// try Yes Exception Report errors , Run to catch, adopt finally Code block 2 sign out
catch Code block
finally Code block 2
// try There are not Exception Report errors , or catch Error reporting in case of abnormality , It's all through finally Code block 3 sign out
finally Code block 3

So the code above finally returns finally The value of the inside , namely a+3 = 4, The program runs , The result of execution is also 4.

finally {
return a + 3;

It can be seen through finally The way the block is copied several times To ensure the implementation of finally!!

copyright:author[ydfind],Please bring the original link to reprint, thank you.