以下代码向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。
答案 0 :(得分:1)
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
转义为未处理。编译器不允许这样做。
必须声明overriden方法以抛出相同的异常(作为父类)或其子类之一。