add demo for execution order of try catch finally

This commit is contained in:
Jason Lu 2025-04-14 10:36:29 +08:00
parent 5a3b711c1d
commit bfd675a438

View File

@ -0,0 +1,27 @@
package main.java.jvm;
/**
* in test method, x will assign to return value, here should be 1 (it will not throw any errors)
* then, the finally block will change x to 3, but the return value will not change
* How finally work is attach the code block in it to try block and catch block
*/
public class TryCatchDemo {
public int test() {
int x=0;
try {
x=1;
return x;
} catch (Exception e) {
x=2;
return x;
} finally {
x=3;
}
}
public static void main(String[] args) {
TryCatchDemo tryCatchDemo = new TryCatchDemo();
System.out.println(tryCatchDemo.test());
}
}