try 关键字
概述
try
关键字用于定义可能抛出异常的代码块,必须与 catch
或 finally
一起使用。
语法格式
try {
// 可能抛出异常的代码
} catch (ExceptionType e) {
// 异常处理
} finally {
// 总是执行的代码
}
// try-with-resources
try (Resource resource = new Resource()) {
// 使用资源的代码
} catch (Exception e) {
// 异常处理
}
基本用法
基本try-catch
public class TryExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println("结果: " + result);
} catch (ArithmeticException e) {
System.out.println("除零错误: " + e.getMessage());
}
System.out.println("程序继续执行");
}
}
try-catch-finally
import java.io.*;
public class TryFinallyExample {
public static void readFile(String filename) {
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
// 读取文件操作
System.out.println("文件读取成功");
} catch (FileNotFoundException e) {
System.out.println("文件未找到: " + e.getMessage());
} finally {
// 清理资源
if (fis != null) {
try {
fis.close();
System.out.println("文件已关闭");
} catch (IOException e) {
System.out.println("关闭文件时出错");
}
}
}
}
}
try-with-resources
import java.io.*;
public class TryWithResourcesExample {
public static void copyFile(String source, String dest) {
try (FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(dest)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
System.out.println("文件复制完成");
} catch (IOException e) {
System.out.println("文件操作失败: " + e.getMessage());
}
// 资源自动关闭
}
}
最佳实践
资源管理:
// 推荐使用try-with-resources try (Scanner scanner = new Scanner(System.in)) { String input = scanner.nextLine(); } // 自动关闭
异常处理层次:
try { // 业务逻辑 } catch (SpecificException e) { // 处理特定异常 } catch (Exception e) { // 处理通用异常 }
try关键字是Java异常处理机制的核心,正确使用它可以编写健壮的程序。