💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
### [在 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 子句永远会执行。