Java 实现方法中的异常处理

Java 实现方法中的异常处理,java,interface,exception-handling,Java,Interface,Exception Handling,下面的代码为抛出异常提供了一个选中的错误: 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;

下面的代码为
抛出异常提供了一个选中的错误:

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做这件事的逻辑是什么——有什么想法吗


蒂亚

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 ref = new SQL2();
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 = getSome();
try {
    ref.ss99();
} catch (IOException e) {
    // handle
}
some ref = new SQL2();
try {
    ref.ss99();
} catch (IOException e) {
    // handle
}
因此,尽管您正在处理接口中声明的异常,但您将允许一个选中的异常,
SQLException
,未经处理而转义。编译器不允许这样做


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

NullPointerException不是选中的异常。