1. 当有finally语句并且try中有return,在执行到return(还未执行)的时候,会先执行finally里面的内容,然后再执行行try中的return。
- package com.and.java.demo;
- public class 测试 {
- public static void main(String[] args) {
- System.out.println(new 测试().test());
- }
- public String test() {
- try {
- System.out.println("try{...}");
- return "try";
- } catch (Exception e) {
- System.out.println("catch{...}");
- return "catch";
- } finally {
- System.out.println("finally{...}");
- }
- }
- }
复制代码 输出:
try{...}
finally{...}
try
2、在1的基础上,如果finally里面也有return语句,则try代码块中的return被屏蔽(不执行),即在try中遇到return的时候,会先执行finally里面的内容(包括finally里面的return语句)。
- package com.and.java.demo;
- public class 测试 {
- public static void main(String[] args) {
- System.out.println(new 测试().test());
- }
- public String test() {
- try {
- System.out.println("try{...}");
- return "try";
- } catch (Exception e) {
- System.out.println("catch{...}");
- return "catch";
- } finally {
- System.out.println("finally{...}");
- return "finally";
- }
- }
- }
复制代码 输出:
try{...}
finally{...}
finally
|