exception handling in the implemented method

天涯浪子 提交于 2019-12-20 06:29:04

问题


The code below gives a checked error to 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?

TIA.


回答1:


The throws keyword indicates that a method or constructor can throw an exception, although it doesn't have to.

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. 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.

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). You therefore don't have to deal with it. You also don't have to deal with NullPointerException because it is an unchecked exception.


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. The compiler cannot allow this.

An overriden method must be declared to throw the same exception (as the parent) or one of its subclasses.



来源:https://stackoverflow.com/questions/25671800/exception-handling-in-the-implemented-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!