Java Throws如何抛出异常
在 Java 中,抛出异常通常使用 throw 关键字(不是 throws,throws 只是声明)。下面分情况说明。
一、使用 throw 抛出异常(手动抛异常)
基本语法
throw new 异常类型("异常信息");
示例
public class Demo {
public static void main(String[] args) {
int age = -1;
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负数");
}
}
}
运行结果:
Exception in thread "main" java.lang.IllegalArgumentException: 年龄不能为负数
二、throw vs throws 的区别
| 关键字 | 作用 | 使用位置 |
|---|---|---|
throw |
真正抛出异常对象 | 方法体内 |
throws |
声明方法可能抛出的异常 | 方法签名上 |
三、throws 声明异常(不处理,交给调用者)
示例
public class Demo {
public static void test() throws Exception {
throw new Exception("发生错误");
}
public static void main(String[] args) throws Exception {
test();
}
}
说明:
test()方法内部抛出了异常- 使用
throws Exception声明 main方法要么继续throws,要么try-catch
四、受检异常 vs 运行时异常
1️⃣ 运行时异常(RuntimeException)
不需要 throws 声明
public static void test() {
throw new RuntimeException("运行时异常");
}
常见运行时异常:
NullPointerExceptionIndexOutOfBoundsExceptionIllegalArgumentException
2️⃣ 受检异常(Checked Exception)
必须处理或声明
public static void readFile() throws IOException {
throw new IOException("文件读取失败");
}
五、自定义异常并抛出
自定义异常类
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
抛出自定义异常
public class Demo {
public static void check(int num) throws MyException {
if (num < 0) {
throw new MyException("数字不能为负数");
}
}
public static void main(String[] args) throws MyException {
check(-1);
}
}
六、总结一句话
✅ 抛出异常用 throw
✅ 声明异常用 throws
✅ 运行时异常可不用声明
✅ 受检异常必须处理或声明
如果你愿意,我也可以帮你画一张 异常抛出流程图 或结合 面试常问点 讲。