java - 编译器在检查异常时没有显示任何错误

标签 java exception core

我正在研究受检查的异常,在这期间发现编译器在受检查的异常上没有显示任何错误并且工作正常。

import java.io.FileNotFoundException;

interface A {
    void f() throws FileNotFoundException;
}

interface B {
    void f() throws InterruptedException;
}

interface C extends A, B {
}

public class Test implements C {
    public void f() {
        System.out.println("Hello world");
    }

    public static void main(String[] args) {
        C obj = new Test();
        obj.f(); // Working fine and printing "Hello World"
    }
}

请告诉我原因,我用谷歌搜索了很多,但没有找到任何东西。

最佳答案

在面向对象的术语中,当您对接口(interface)进行编程(即实现接口(interface)或扩展接口(interface))时,您不能比接口(interface)更具限制性。但是,您可以减少限制。因此,在您的示例中,接口(interface)的方法可能会也可能不会抛出 FileNotFoundException 和/或 InterruptedException,但您的实现方法不会抛出异常。请注意,如果您的实现方法抛出 FileNotFoundException 和/或 InterruptedException,则完全没问题,但如果它抛出其他异常,则不允许。这意味着您的实现可以等于或小于接口(interface)的限制,但不能比接口(interface)的限制更大。

另请注意,当有人通过扩展接口(interface)类型(C)的变量或通过类类型(Test)的变量使用您的方法 f() 时,他们不需要处理异常。但是,如果他们通过接口(interface)类型 A 或 B 的变量使用您的方法 f(),则需要处理异常。

A obj = new Test(); 
obj.f(); // need to handle FileNotFoundException

B obj = new Test();
obj.f(); // need to handle InterruptedException

C obj = new Test(); 
obj.f(); // don't need to handle any of the exceptions

Test obj = new Test(); 
obj.f(); // don't need to handle any of the exceptions

更多说明: C.f() 不抛出异常的原因是它的父接口(interface)抛出不同的异常。因此,根据“接口(interface)的实现或扩展不能有更多限制但可以更少限制”这一论点,C.f() 减少限制的唯一方法是不抛出异常。否则,它将比至少其父接口(interface)之一更具限制性。 另一方面,如果 C 的 parent 都抛出相同的异常,那么 C.f() 也需要抛出这些异常。但是,实现仍然可以选择不抛出异常。

import java.io.FileNotFoundException;

interface A{
    void f() throws FileNotFoundException;
}

interface B {
    void f() throws FileNotFoundException;
}

interface C extends A, B {
}

public class Test implements C {
    public void f() {
        System.out.println("Hello world");
    }

    public static void main(String[] args) {
        C obj = new Test();
        obj.f(); // Compilation error, unhandled exception

        Test obj = new Test();
        obj.f(); // No error
    }
}

关于java - 编译器在检查异常时没有显示任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42550454/

相关文章:

java - StackTrace 中的 "Number of locked synchronizers = 1"是什么意思?

linux - 无法找到安装了 abrt-hook-cpp 的核心文件

java - 命令行编译时无法使用包函数

java - 将 BLOB 加载到图库 android

java - 如何获得 Maven 多模块项目的完整代码覆盖率

java - 数组/vector 作为方法参数

delphi - 即使我使用 try..except 也会出现异步套接字错误 10049

java - 在 JSF 页面中显示错误并继续呈现它,而不是重定向到单独的错误页面

java - 作用域局部变量和条件的问题

Java数组索引越界异常排序