温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java Throws 抛出如何捕

发布时间:2026-10-07 01:12:16 来源:亿速云 阅读:91 作者:小樊 栏目:编程语言

在 Java 里,throws 只是“声明可能抛出的异常”,真正要“捕获”异常,需要在调用该方法的地方使用 try–catch。

下面分几种情况说明。


一、基本用法(try–catch 捕获)

方法使用 throws

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 抛出的异常,由调用者捕获


二、main 方法 throws(不推荐但常见)

public static void main(String[] args) throws Exception {
    test();
}

⚠️ 这样 JVM 会直接处理异常,程序会终止
❌ 没有被“捕获”


三、受检异常 vs 非受检异常

1️⃣ 受检异常(必须处理)

public void read() throws IOException {
}

✅ 调用时必须:

  • try-catch
  • 或继续 throws

2️⃣ 非受检异常(RuntimeException)

public void test() throws RuntimeException {
}

✅ 可以捕获,也可以不捕获


四、多重异常捕获

try {
    test();
} catch (IOException e) {
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
}

⚠️ 子类异常必须写在前面


五、try-with-resources(推荐)

try (FileInputStream fis = new FileInputStream("a.txt")) {
    // 自动关闭
} catch (IOException e) {
    e.printStackTrace();
}

六、常见错误

❌ 以为 throws 能捕获异常
✅ throws 只是“向上抛”

❌ catch 顺序写反
✅ 先子类后父类


如果你有 具体代码(比如某个方法 throws 了什么异常),我可以直接帮你改。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手