java异常如何抛出
抛出异常的方法
在Java中,异常抛出主要通过throw关键字实现。以下是几种常见的抛出异常的方式:

使用throw关键字抛出异常

if (condition) {
throw new IllegalArgumentException("参数不合法");
}
自定义异常类
自定义异常需继承Exception或RuntimeException类:
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
// 使用时
throw new CustomException("自定义异常信息");
在方法声明中声明抛出异常
使用throws关键字在方法签名中声明可能抛出的异常:
public void riskyMethod() throws IOException {
// 可能抛出IOException的代码
}
异常处理的最佳实践
- 检查性异常(Checked Exception)需强制处理或声明抛出,如
IOException。 - 非检查性异常(Unchecked Exception)通常继承
RuntimeException,可不强制处理。 - 抛出的异常应包含清晰的错误信息,便于调试。
- 避免捕获异常后不处理(空的catch块)。
示例代码
public class Example {
public static void validateAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负数");
}
}
public static void main(String[] args) {
try {
validateAge(-5);
} catch (IllegalArgumentException e) {
System.out.println("捕获异常: " + e.getMessage());
}
}
}






