java 如何设定异常
异常处理基础
在Java中,异常通过try-catch-finally块处理。try包裹可能抛出异常的代码,catch捕获并处理异常,finally确保资源释放。
try {
// 可能抛出异常的代码
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("除零错误: " + e.getMessage());
} finally {
System.out.println("资源清理");
}
自定义异常
通过继承Exception(受检异常)或RuntimeException(非受检异常)创建自定义异常。

public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 使用自定义异常
try {
throw new CustomException("自定义异常示例");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
抛出异常
使用throw主动抛出异常,通常在方法内验证逻辑不满足时使用。
public void validateAge(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负数");
}
}
异常传播
方法声明中通过throws指明可能抛出的异常,调用者需处理或继续传播。

public void readFile() throws IOException {
// 文件操作可能抛出IOException
Files.readAllLines(Paths.get("file.txt"));
}
多异常捕获
Java 7+支持单catch块捕获多个异常,用|分隔。
try {
// 可能抛出多种异常的代码
} catch (IOException | SQLException e) {
System.out.println("IO或数据库错误: " + e.getMessage());
}
异常链
通过构造器传递原始异常,保留完整的堆栈信息。
try {
// 代码块
} catch (IOException e) {
throw new CustomException("包装异常", e); // 传递原始异常
}






