验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Java Throws检查异常规则

阅读:213 来源:乙速云 作者:代码code

Java Throws检查异常规则

在 Java 中,“Throws 检查异常规则”主要围绕 checked exception(受检异常)声明与处理机制展开。下面系统性地说明。


一、什么是“检查异常(Checked Exception)”

Java 把异常分为两大类:

类型 说明 示例
Checked Exception 编译期必须处理 IOException, SQLException
Unchecked Exception 编译期不强制处理 RuntimeException, NullPointerException

只有 Checked Exception 才受 throws 规则约束


二、throws 的基本作用

throws 用于方法声明处,表示:

该方法可能抛出某些异常,但不在方法内处理,交给调用者处理。

void readFile() throws IOException {
    FileInputStream in = new FileInputStream("a.txt");
}

三、核心规则(重点)

✅ 规则 1:Checked Exception 必须二选一

如果一个方法可能抛出 checked exception,必须:

  1. 在方法内 try-catch 处理
  2. 用 throws 声明抛出

❌ 否则编译错误

// 编译错误
void test() {
    throw new IOException(); // IOException 是 checked
}

✅ 修正方式一:catch

void test() {
    try {
        throw new IOException();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

✅ 修正方式二:throws

void test() throws IOException {
    throw new IOException();
}

✅ 规则 2:调用者必须继续处理

如果一个方法 throws 了 checked exception

  • 调用者要么:
    • 继续 throws
    • 要么 try-catch
void a() throws IOException {
    b();
}

void b() throws IOException {
    throw new IOException();
}

✅ 或:

void a() {
    try {
        b();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

✅ 规则 3:可以 throws 多个异常

void test() throws IOException, SQLException {
    ...
}

✅ 规则 4:throws 可以声明父类异常

void test() throws Exception {
    throw new IOException();
}

⚠️ 不推荐过度使用 Exception


✅ 规则 5:子类重写方法不能抛出更宽的异常

方法重写时的异常规则(非常重要)

class Parent {
    void m() throws IOException {}
}

class Child extends Parent {
    @Override
    void m() throws IOException {}        // ✅
    // void m() throws Exception {}      // ❌ 编译错误
}

✅ 子类方法可以:

  • 不抛异常
  • 抛相同或更窄的异常

❌ 不能抛比父类更宽泛的 checked exception


四、Unchecked Exception 不受 throws 约束

void test() {  // 不需要 throws
    throw new RuntimeException();
}

✅ 虽然可以写 throws RuntimeException,但没有意义


五、main 方法的特殊点

main 也可以 throws

public static void main(String[] args) throws IOException {
    ...
}

✅ 如果异常未被捕获,JVM 会终止程序并打印异常栈


六、常见面试总结版

Java 中 throws 对检查异常的规则是什么?

✅ 答案要点:

  1. Checked Exception 必须被处理或声明
  2. throws 用于声明方法可能抛出的 checked 异常
  3. 调用者必须处理或继续声明
  4. 重写方法不能抛出比父类更宽的 checked 异常
  5. RuntimeException 不受该规则限制

如果你愿意,我也可以:

  • 对比图 总结 checked / unchecked
  • 结合 真实业务代码 示例
  • throws vs throw 区别
  • 或出几道 面试题 给你练手
分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>