throw :用于主动抛出异常,适合在检测到错误条件时通知调用者 => 不用代码继续运行时使用
import java.io.FileReader;
import java.io.IOException;
// 自定义异常类
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class ExceptionHandlingExample {
public static void main(String[] args) {
// 示例 1: 捕获非受检异常 (RuntimeException)
try {
int result = divide(10, 0); // 可能抛出 ArithmeticException
System.out.println("结果: " + result);
} catch (ArithmeticException e) {
System.out.println("捕获到运行时异常: " + e.getMessage());
}
// 示例 2: 处理受检异常 (Checked Exception)
try {
readFile("nonexistent.txt"); // 文件不存在会抛出 IOException
} catch (IOException e) {
System.out.println("捕获到 IO 异常: " + e.getMessage());
} finally {
System.out.println("finally 块总是执行");
}
// 示例 3: 抛出自定义异常
try {
validateAge(-5); // 年龄为负数时抛出自定义异常
} catch (CustomException e) {
System.out.println("捕获到自定义异常: " + e.getMessage());
}
}
// 方法 1: 可能抛出非受检异常的方法
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("除数不能为零");
}
return a / b;
}
// 方法 2: 可能抛出受检异常的方法
public static void readFile(String fileName) throws IOException {
FileReader reader = null;
try {
reader = new FileReader(fileName);
System.out.println("文件读取成功");
} finally {
if (reader != null) {
reader.close(); // 确保资源释放
}
}
}
// 方法 3: 抛出自定义异常的方法
public static void validateAge(int age) throws CustomException {
if (age < 0) {
throw new CustomException("年龄不能为负数");
}
System.out.println("年龄验证通过: " + age);
}
}