在 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不需要 throws 声明
public static void test() {
throw new RuntimeException("运行时异常");
}
常见运行时异常:
NullPointerExceptionIndexOutOfBoundsExceptionIllegalArgumentException必须处理或声明
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
✅ 运行时异常可不用声明
✅ 受检异常必须处理或声明
如果你愿意,我也可以帮你画一张 异常抛出流程图 或结合 面试常问点 讲。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。