JavaSE进阶
9.6 finally与return
执行顺序:
1、执行try,catch,给“返回值”临时变量赋值
2、执行finally
3、return
return语句两个作用:给返回值赋值,结束方法运行
9.6.1 从finally的return回来
示例代码:
package com.atguigu.exception; public class TestReturn { public static void main(String[] args) { int result = test("a"); System.out.println(result); } public static int test(String str){ try{ Integer.parseInt(str); return 1; }catch(NumberFormatException e){ return -1; }finally{ System.out.println("test结束"); return 0; } } } |
运行结果:
test结束 0 |
9.6.2 从catch的return回来
示例代码
package com.atguigu.exception; public class TestReturn { public static void main(String[] args) { int result = test("a"); System.out.println(result); } public static int test(String str){ try{ Integer.parseInt(str); return 1; }catch(NumberFormatException e){ return -1; }finally{ System.out.println("test结束"); } } } |
运行结果:
test结束 -1 |
9.6.3 从try的return回来
示例代码:
package com.atguigu.exception; public class TestReturn { public static void main(String[] args) { int result = test("12"); System.out.println(result); } public static int test(String str){ try{ Integer.parseInt(str); return 1; }catch(NumberFormatException e){ return -1; }finally{ System.out.println("test结束"); } } } |
运行结果:
test结束 1 |