Java中throws 与 throw 的区别与用法示例详解
作者:菜鸟不学编程
一、先看最短总结
| 关键字 | 作用 | 出现位置 | 常用于 |
|---|---|---|---|
| throw | 抛出一个异常对象(实际动作) | 方法体内部 | 立即抛出某个异常 |
| throws | 声明方法可能抛出的异常类型(承诺/说明) | 方法声明处 | 告诉调用者“我可能抛异常” |
一句话记忆:
throw 是“扔出异常”,throws 是“声明可能会扔异常”。
二、throw:真正“扔出”异常
throw 用于在方法内部创建并抛出一个异常对象,程序执行到 throw 就会立刻中断,并把异常抛给调用者,或者被当前方法内部的 try-catch 捕获。
语法:
throw new 异常类型("异常信息");示例 1:手动抛出异常
public class ThrowExample {
public static void main(String[] args) {
int age = -5;
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负数!");
}
System.out.println("年龄是:" + age);
}
}输出:
Exception in thread "main" java.lang.IllegalArgumentException: 年龄不能为负数!
at ThrowExample.main(ThrowExample.java:5)
解释:
throw立刻抛出一个异常对象。- 后续代码不会执行。
示例 2:配合 try-catch 捕获异常
public class ThrowExample {
public static void main(String[] args) {
try {
checkAge(-5);
} catch (IllegalArgumentException e) {
System.out.println("捕获到异常:" + e.getMessage());
}
}
public static void checkAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("年龄不能为负数!");
}
System.out.println("年龄是:" + age);
}
}输出:
捕获到异常:年龄不能为负数!
🎯 要点:
throw后面是一个异常对象。- 一旦执行
throw,程序会跳出当前方法,除非被 try-catch 捕获。
三、throws:声明可能抛出的异常
throws 并不真正抛出异常,而是用于声明“我这个方法 可能 抛出某种异常”,提醒调用者必须关注这个异常。
语法:
修饰符 返回值类型 方法名(参数列表) throws 异常类型1, 异常类型2, ... {
// 方法体
}示例:声明方法可能抛异常
比如读文件时,FileReader 的构造方法可能抛 FileNotFoundException,你就必须用 throws 声明:
import java.io.FileReader;
import java.io.FileNotFoundException;
public class ThrowsExample {
public static void main(String[] args) {
try {
readFile("test.txt");
} catch (FileNotFoundException e) {
System.out.println("捕获到异常:" + e.getMessage());
}
}
public static void readFile(String path) throws FileNotFoundException {
FileReader fr = new FileReader(path);
System.out.println("文件读取成功!");
}
}如果不写 try-catch,而又不在方法签名里写 throws,编译器会报错。
🎯 要点:
throws出现在方法声明处,表示 可能 抛出的异常类型。- 调用方要么:
- 用
try-catch捕获; - 或者继续在自己的方法上声明
throws。
- 用
四、throw 和 throws 的区别
| 比较 | throw | throws |
|---|---|---|
| 位置 | 方法体内 | 方法声明处 |
| 作用 | 真正抛出异常 | 声明可能会抛异常 |
| 后面跟 | 异常对象 | 异常类型(类名) |
| 数量 | 一次只能抛一个异常对象 | 可声明多个异常类型,用逗号分隔 |
| 是否是执行动作 | 是 | 否,仅声明 |
五、Checked 与 Unchecked 异常与 throws 的关系
Java 异常分两类:
- Checked Exception(受检异常)
- 编译器检查
- 必须用 try-catch 或 throws
- 如:
IOException,SQLException
- Unchecked Exception(运行时异常)
- 编译器不会强制检查
- 不一定需要写 throws
- 如:
NullPointerException,IllegalArgumentException
⚠️ throws 主要用于声明 Checked Exception。
示例:throws 通常声明 Checked Exception
public void readData() throws IOException {
// code that may throw IOException
}
而对于 RuntimeException(Unchecked),一般不用写 throws:
public void divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("除数不能为零!");
}
}
六、经典面试题
throw 和 throws 有什么区别?
简答:
throw 用于方法体内,真正抛出异常对象;
throws 用于方法声明处,表示该方法可能抛出哪些异常类型,提醒调用者处理。
✅ 重点记忆
- throw:方法内部,真正扔出一个异常对象
- throws:方法声明处,告诉外部“我可能会扔异常”
- Checked Exception → 必须 throws 或 try-catch
- Unchecked Exception → 可写 throw,不一定写 throws
这样,你是不是对 throw 和 throws 一下就清楚了呢?😎
到此这篇关于Java中throws 与 throw 的区别与用法示例详解的文章就介绍到这了,更多相关java throws 与 throw 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
