throw 与 throws 的区别?
throw和throws均是 Java 中用于 “异常处理” 的关键字,核心差异在于 “作用、使用位置、语法”:
# 1. 核心区别
| 对比维度 | throw | throws |
|---|---|---|
| 核心作用 | 手动抛出具体的异常对象(触发异常) | 声明方法可能抛出的异常类型(告知调用者) |
| 使用位置 | 方法体内部(可在任意代码块中使用) | 方法声明处(方法名后,参数列表与大括号之间) |
| 语法格式 | throw new 异常类(异常信息);(只能抛出一个异常对象) | 方法返回值 方法名(参数) throws 异常类1, 异常类2...;(可声明多个异常类型) |
| 异常类型 | 可抛出 checked 异常(需处理)和 unchecked 异常(无需处理) | 可声明 checked 异常(强制调用者处理)和 unchecked 异常(可选处理) |
| 执行效果 | 执行到 throw 时,立即终止当前代码块,抛出异常 | 仅声明异常,不触发异常,异常由方法内部的 throw 或代码错误触发 |
# 2. 示例
java
运行
// 1. throws:声明方法可能抛出的异常
public static void readFile(String path) throws FileNotFoundException, IOException {
File file = new File(path);
if (!file.exists()) {
// 2. throw:手动抛出具体异常对象
throw new FileNotFoundException("文件不存在:" + path);
}
// 读取文件(可能抛出IOException)
FileReader reader = new FileReader(file);
}
// 调用者处理异常
public static void main(String[] args) {
try {
readFile("test.txt");
} catch (FileNotFoundException e) {
System.out.println("处理文件不存在异常:" + e.getMessage());
} catch (IOException e) {
System.out.println("处理IO异常:" + e.getMessage());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 3. 关键注意事项
throw抛出的 checked 异常(如FileNotFoundException),必须在方法上用throws声明,或在方法内用try-catch处理;throws声明的异常,调用者必须处理(try-catch)或继续用throws声明(向上传递);throw抛出的 unchecked 异常(如NullPointerException、RuntimeException),可不用throws声明,调用者也可不用处理(但可能导致程序崩溃)。
上次更新: 12/30/2025