是的,无论 try 中是否有 return,finally 中的语句都会执行。finally 语句块通常用于释放资源或清理代码。

例如,如果 try 块中打开了一个文件,那么在 finally 块中应该关闭该文件,以确保文件资源被正确释放。

代码示例:

public class Example {
    public static void main(String[] args) {
        try {
            // 打开文件
            File file = new File("file.txt");
            FileReader reader = new FileReader(file);
            // ... 处理文件内容
            return;
        } catch (FileNotFoundException e) {
            // 处理文件未找到的异常
        } finally {
            // 关闭文件
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // 处理关闭文件时发生的异常
                }
            }
        }
    }
}

在上面的示例中,即使在 try 块中执行了 return 语句,finally 块中的代码仍然会执行,以确保文件资源被释放。

Try-Catch-Finally 中 return 语句的行为

原文地址: http://www.cveoy.top/t/topic/mAw0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录