在 Java 中,throws 用于声明方法可能抛出的异常,把异常处理的责任交给调用者。下面从“是什么、怎么用、如何处理”三个层面讲清楚。
throws 是什么throws 是方法签名的一部分,用来声明异常:
public void readFile() throws IOException {
// 可能抛出 IOException
}
作用:
throws 的常见用法public void test() throws IOException {
FileInputStream fis = new FileInputStream("a.txt");
}
调用时必须处理:
public static void main(String[] args) {
try {
test();
} catch (IOException e) {
e.printStackTrace();
}
}
或者继续 throws:
public static void main(String[] args) throws IOException {
test();
}
public void method() throws IOException, SQLException {
}
public void method() throws RuntimeException {
}
运行时异常(
RuntimeException)不需要throws,但写了也没问题
throws 和 throw 的区别(重点)| 关键字 | 作用 |
|---|---|
throws |
声明异常(方法上) |
throw |
真正抛出异常(方法内) |
public void test() throws Exception {
if (true) {
throw new Exception("出错了");
}
}
throws 异常如何处理(核心)try-catch 处理(推荐)try {
method();
} catch (IOException e) {
System.out.println("处理异常");
}
throws 往上抛public void a() throws IOException {
b();
}
public void b() throws IOException {
// 可能抛异常
}
main 抛出(不推荐生产用)public static void main(String[] args) throws Exception {
}
✅ 底层方法 throws,上层 try-catch
✅ 不要在 main 随便 throws
✅ 受检异常必须处理或声明
❌ 不要吞异常(catch 里什么都不做)
如果你有具体代码(比如某个方法不知道怎么处理 throws),可以直接贴出来,我可以帮你改。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。