繁体   English   中英

实现方法中的异常处理

[英]exception handling in the implemented method

下面的代码给出了一个检查错误, throws Exception

import java.io.IOException;

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws Exception {}
// ...
}

而下面的一个可以编译:

import java.io.IOException;

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws NullPointerException {}
// ...
}

Java在执行什么逻辑上有什么想法?

TIA。

throws关键字指示方法或构造函数可以抛出异常,尽管不是必须的。

让我们从第二个片段开始

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws NullPointerException {}
}

考虑

some ref = getSome();
try {
    ref.ss99();
} catch (IOException e) {
    // handle
}

您需要使用的只是界面的some 我们(编译器)不知道它所引用的对象的实际实现。 因此,我们必须确保处理可能引发的任何IOException

如果是

SQL2 ref = new SQL2();
ref.ss99();

您正在使用实际的实现。 此实现保证了它永远不会抛出IOException (通过不声明它)。 因此,您不必处理它。 您也不必处理NullPointerException因为它是未经检查的异常。


关于您的第一个片段,略有变化

interface some {
    void ss99() throws IOException;
}

public class SQL2 implements some {
    @Override
    public void ss99 () throws Exception { throw new SQLException(); }
}

考虑

some ref = new SQL2();
try {
    ref.ss99();
} catch (IOException e) {
    // handle
}

因此,尽管您正在处理接口中声明的异常,但是您将让未经检查的异常SQLException逸出。 编译器不允许这样做。

必须声明一个重写的方法以引发相同的异常(作为父类)或其子类之一。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM