在 Java 里,throws 只是“声明可能抛出的异常”,真正要“捕获”异常,需要在调用该方法的地方使用 try–catch。
下面分几种情况说明。
public class Demo {
public static void test() throws Exception {
throw new Exception("出错了");
}
public static void main(String[] args) {
try {
test(); // 调用 throws 方法
} catch (Exception e) {
System.out.println("捕获到异常:" + e.getMessage());
}
}
}
✅ throws 抛出的异常,由调用者捕获
public static void main(String[] args) throws Exception {
test();
}
⚠️ 这样 JVM 会直接处理异常,程序会终止
❌ 没有被“捕获”
public void read() throws IOException {
}
✅ 调用时必须:
try-catchthrowspublic void test() throws RuntimeException {
}
✅ 可以捕获,也可以不捕获
try {
test();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
⚠️ 子类异常必须写在前面
try (FileInputStream fis = new FileInputStream("a.txt")) {
// 自动关闭
} catch (IOException e) {
e.printStackTrace();
}
❌ 以为 throws 能捕获异常
✅ throws 只是“向上抛”
❌ catch 顺序写反
✅ 先子类后父类
如果你有 具体代码(比如某个方法 throws 了什么异常),我可以直接帮你改。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。