ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### [在 return 中使用 finally](https://lingcoder.gitee.io/onjava8/#/book/15-Exceptions?id=%e5%9c%a8-return-%e4%b8%ad%e4%bd%bf%e7%94%a8-finally) 因为 finally 子句总是会执行,所以可以从一个方法内的多个点返回,仍然能保证重要的清理工作会执行: ~~~ // exceptions/MultipleReturns.java public class MultipleReturns { public static void f(int i) { System.out.println( "Initialization that requires cleanup"); try { System.out.println("Point 1"); if(i == 1) return; System.out.println("Point 2"); if(i == 2) return; System.out.println("Point 3"); if(i == 3) return; System.out.println("End"); return; } finally { System.out.println("Performing cleanup"); } } public static void main(String[] args) { for(int i = 1; i <= 4; i++) f(i); } } ~~~ 输出为: ~~~ Initialization that requires cleanup Point 1 Performing cleanup Initialization that requires cleanup Point 1 Point 2 Performing cleanup Initialization that requires cleanup Point 1 Point 2 Point 3 Performing cleanup Initialization that requires cleanup Point 1 Point 2 Point 3 End Performing cleanup ~~~ 从输出中可以看出,从何处返回无关紧要,finally 子句永远会执行。