From bfd675a4387cab7e2d2b3606221873ceffdd852e Mon Sep 17 00:00:00 2001 From: Jason Lu Date: Mon, 14 Apr 2025 10:36:29 +0800 Subject: [PATCH] add demo for execution order of try catch finally --- src/main/java/jvm/TryCatchDemo.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/jvm/TryCatchDemo.java diff --git a/src/main/java/jvm/TryCatchDemo.java b/src/main/java/jvm/TryCatchDemo.java new file mode 100644 index 0000000..bfa2282 --- /dev/null +++ b/src/main/java/jvm/TryCatchDemo.java @@ -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()); + } +}