java如何编写异常
在Java中编写异常处理代码是确保程序健壮性的关键部分。以下是几种常见的方法和示例:

使用try-catch块捕获异常
try {
int result = 10 / 0; // 触发ArithmeticException
} catch (ArithmeticException e) {
System.out.println("除零错误: " + e.getMessage());
}
使用多重catch块处理不同类型的异常
try {
int[] arr = new int[5];
arr[10] = 50; // 触发ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界: " + e.getMessage());
} catch (Exception e) {
System.out.println("通用异常: " + e.getMessage());
}
使用finally块确保资源释放
FileInputStream file = null;
try {
file = new FileInputStream("test.txt");
// 文件操作
} catch (FileNotFoundException e) {
System.out.println("文件未找到: " + e.getMessage());
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
System.out.println("关闭文件时出错: " + e.getMessage());
}
}
}
自定义异常类
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 使用自定义异常
try {
throw new CustomException("这是一个自定义异常");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
使用throws声明异常
public void riskyMethod() throws IOException {
throw new IOException("IO异常示例");
}
// 调用方法时处理异常
try {
riskyMethod();
} catch (IOException e) {
System.out.println("捕获IO异常: " + e.getMessage());
}
try-with-resources语句
try (FileInputStream file = new FileInputStream("test.txt")) {
// 自动资源管理
} catch (FileNotFoundException e) {
System.out.println("文件未找到: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO错误: " + e.getMessage());
}
每种方法适用于不同的场景,选择合适的方式取决于具体需求和异常类型。自定义异常特别适合需要特定业务逻辑错误处理的场景,而try-with-resources简化了资源管理代码。






