java 流程控制中,异常处理通过 try-catch-finally 结构实现,将正常逻辑与错误处理分离。具体做法是在可能出错的代码块外包裹 try,在 catch 中捕获特定异常并执行恢复或日志记录,确保程序不会因未处理错误而崩溃。若需保证资源释放,必须使用 finally 块,无论是否发生异常都会执行。

try-catch 如何捕获和处理运行时异常?
try-catch 用于捕获并处理程序运行期间抛出的异常,防止程序终止。开发者只需将可能抛出异常的代码放入 try 块,并在 catch 块中指定要捕获的异常类型及处理逻辑。例如,捕获 ArithmeticException 可以处理除以零的错误,程序会继续执行后续代码。

public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught exception: " + e.getMessage());
}
System.out.println("Program continues...");
}
}
预期结果:程序输出 "Caught exception: / by zero" 和 "Program continues...",不会抛出未捕获异常导致崩溃。
finally 块在异常处理中的作用是什么?
finally 块用于定义无论是否发生异常都必须执行的代码,通常用于资源清理。它紧跟在 try-catch 之后,即使 try 或 catch 中有 return 语句,finally 仍会执行。这确保了如文件流、数据库连接等资源能被正确关闭,避免内存泄漏。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。

import java.io.*;
public class FinallyDemo {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("test.txt"));
String line = reader.readLine();
System.out.println("Read: " + line);
} catch (IOException e) {
System.out.println("IO Error: " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println("Close Error: " + e.getMessage());
}
}
System.out.println("Cleanup done.");
}
}
}
预期结果:无论文件是否存在,程序都会输出 "Cleanup done.",并确保资源被释放。
当 finally 块中包含 return 时,返回值如何确定?
当 finally 块中包含 return 语句时,它会覆盖 try 或 catch 中的返回值,最终方法返回 finally 块中的值。这是 Java 异常处理的一个关键行为,可能导致意外结果,因此应避免在 finally 中使用 return。例如,若 try 返回 1,但 finally 返回 2,则方法实际返回 2。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










