Java中finally与return的执行顺序
发布时间:2020-12-15 02:36:43 所属栏目:Java 来源:网络整理
导读:在 Java 的异常处理中,try、catch 和 finally 是按顺序执行的。如果 try 中没有异常,则顺序为 try→finally,如果 try 中有异常,则顺序为 try→catch→finally。但是当 try、catch、finally 中加入 return 之后,return 和 finally 的执行顺序让很多人混淆
在 Java 的异常处理中,try、catch 和 finally 是按顺序执行的。如果 try 中没有异常,则顺序为 try→finally,如果 try 中有异常,则顺序为 try→catch→finally。但是当 try、catch、finally 中加入 return 之后,return 和 finally 的执行顺序让很多人混淆不清。下面来分别说明一下。1. try 和 catch 中带有?return1)try 中带有 returnpublic class tryDemo { public static int show() { try { return 1; } finally { System.out.println("执行finally模块"); } } public static void main(String args[]) { System.out.println(show()); } }输出结果如下:
执行finally模块 public class tryDemo { public static int show() { try { int a = 8 / 0; return 1; } catch (Exception e) { return 2; } finally { System.out.println("执行finally模块"); } } public static void main(String args[]) { System.out.println(show()); } }输出结果为:
执行finally模块 注意:可以使用编译器的 Debug 功能查看详细过程。如果不了解如何使用 Debug 功能可参考《Java Eclipse如何调试代码》一节。 2. finally 中带有 returnpublic class tryDemo { public static int show() { try { int a = 8 / 0; return 1; } catch (Exception e) { return 2; } finally { System.out.println("执行finally模块"); return 0; } } public static void main(String args[]) { System.out.println(show()); } }输出结果如下:
执行finally模块 注意:finally 代码块中最好不要包含 return 语句,否则程序会提前退出。 3. finally 中改变返回值下面先来看 try 代码块或者 catch 代码块中的返回值是普通变量时,代码如下:public class tryDemo { public static int show() { int result = 0; try { return result; } finally { System.out.println("执行finally模块"); result = 1; } } public static void main(String args[]) { System.out.println(show()); } }输出结果为:
执行finally模块 当返回值类型是引用类型时,结果也是一样的,代码如下: public class tryDemo { public static Object show() { Object obj = new Object(); try { return obj; } finally { System.out.println("执行finally模块"); obj = null; } } public static void main(String args[]) { System.out.println(show()); } }输出结果为:
执行finally模块 总结为以下几条:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |