简体   繁体   English

实现方法中的异常处理

[英]exception handling in the implemented method

The code below gives a checked error to throws Exception : 下面的代码给出了一个检查错误, throws Exception

import java.io.IOException;

interface some {
    void ss99() throws IOException;
}

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

while the one below compiles fine: 而下面的一个可以编译:

import java.io.IOException;

interface some {
    void ss99() throws IOException;
}

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

On what logic is Java doing this-- any ideas? Java在执行什么逻辑上有什么想法?

TIA. TIA。

The throws keyword indicates that a method or constructor can throw an exception, although it doesn't have to. throws关键字指示方法或构造函数可以抛出异常,尽管不是必须的。

Let's start with your second snippet 让我们从第二个片段开始

interface some {
    void ss99() throws IOException;
}

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

Consider 考虑

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

All you have to work with is with your interface some . 您需要使用的只是界面的some We (the compiler) don't know the actual implementation of the object it is referencing. 我们(编译器)不知道它所引用的对象的实际实现。 As such, we have to make sure to handle any IOException that may be thrown. 因此,我们必须确保处理可能引发的任何IOException

In the case of 如果是

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

you're working with the actual implementation. 您正在使用实际的实现。 This implementation guarantees that it will never throw an IOException (by not declaring it). 此实现保证了它永远不会抛出IOException (通过不声明它)。 You therefore don't have to deal with it. 因此,您不必处理它。 You also don't have to deal with NullPointerException because it is an unchecked exception. 您也不必处理NullPointerException因为它是未经检查的异常。


Regarding your first snippet, slightly changed 关于您的第一个片段,略有变化

interface some {
    void ss99() throws IOException;
}

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

Consider 考虑

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

So although you are handling the exception declared in the interface, you would be letting a checked exception, SQLException , escape unhandled. 因此,尽管您正在处理接口中声明的异常,但是您将让未经检查的异常SQLException逸出。 The compiler cannot allow this. 编译器不允许这样做。

An overriden method must be declared to throw the same exception (as the parent) or one of its subclasses. 必须声明一个重写的方法以引发相同的异常(作为父类)或其子类之一。

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

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