java中的try如何使用
try 的基本语法结构
在 Java 中,try 用于包裹可能抛出异常的代码块,通常与 catch 和 finally 配合使用。基本语法如下:
try {
// 可能抛出异常的代码
} catch (ExceptionType e) {
// 处理特定类型的异常
} finally {
// 无论是否发生异常都会执行的代码(可选)
}
try-catch 捕获异常
try 块中包含可能抛出异常的代码,catch 块用于捕获并处理异常。可以指定具体的异常类型(如 IOException、NullPointerException),也可以捕获所有异常(Exception)。
try {
int result = 10 / 0; // 抛出 ArithmeticException
} catch (ArithmeticException e) {
System.out.println("除零错误: " + e.getMessage());
}
多 catch 块处理不同异常
可以定义多个 catch 块,按顺序匹配异常类型。子类异常需放在父类异常之前。
try {
// 可能抛出多种异常的代码
} catch (IOException e) {
System.out.println("IO 异常: " + e);
} catch (SQLException e) {
System.out.println("SQL 异常: " + e);
} catch (Exception e) {
System.out.println("其他异常: " + e);
}
try-finally 资源清理
finally 块中的代码无论是否发生异常都会执行,常用于释放资源(如关闭文件、数据库连接)。
FileInputStream file = null;
try {
file = new FileInputStream("test.txt");
// 操作文件
} finally {
if (file != null) {
file.close(); // 确保资源被释放
}
}
try-with-resources 自动管理资源
Java 7 引入的 try-with-resources 语法可自动关闭实现了 AutoCloseable 接口的资源,无需显式调用 close()。
try (FileInputStream file = new FileInputStream("test.txt")) {
// 操作文件
} catch (IOException e) {
System.out.println("IO 异常: " + e);
}
嵌套 try-catch 块
try-catch 可以嵌套使用,内层异常未被捕获时会传递给外层。

try {
try {
int[] arr = new int[1];
arr[2] = 3; // 抛出 ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("内层捕获: " + e);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("外层捕获: " + e);
}
注意事项
catch块必须紧接try块,且至少需要一个catch或finally。finally块中避免返回语句或抛出异常,否则会覆盖try或catch中的行为。try-with-resources支持声明多个资源,用分号分隔。






