在 Java 里你提到 “Throws 抛出为啥报错”,一般不是 throws 本身有问题,而是用法或位置不对。下面把常见报错原因给你梳理一下。
throws 和 throw 搞混了(最常见)public void test() {
throws new Exception(); // 报错
}
public void test() throws Exception {
throw new Exception();
}
区别:
throw:在方法内部真正抛出一个异常对象throws:在方法声明处声明“这个方法可能会抛什么异常”throws 写错位置public void test() {
throws IOException; // 报错
}
public void test() throws IOException {
// 方法体
}
throws 只能在方法签名上。
throws 范围不对class A {
public void m() throws IOException {}
}
class B extends A {
@Override
public void m() throws Exception {} // 报错
}
子类重写方法:
✅ 正确:
@Override
public void m() throws FileNotFoundException {}
main 方法没处理受检异常public static void main(String[] args) {
readFile(); // 报错
}
static void readFile() throws IOException {}
方式 1:继续 throws
public static void main(String[] args) throws IOException
方式 2:try-catch
try {
readFile();
} catch (IOException e) {
e.printStackTrace();
}
throwspublic void test() throws NullPointerException { } // 没必要
RuntimeException 及其子类不需要声明 throws。
throws 或 try-catchthrows 写在方法体里如果你愿意,可以把 具体报错代码 + 报错信息 发出来,我可以直接帮你指出是哪一条导致的。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。