这是一段不能编译的代码:
void multiCatch()
{
try {
throwIOFile();
}
// FileNotFoundException extends IOException, hence this
// does not compile ("alternatives" related by sub classing):
catch (IOException | FileNotFoundException e) { }
}
void throwIOFile() throws IOException, FileNotFoundException
{}
如果异常类型没有通过子类关联,一切都像魅力一样工作。如果您将IOException
我的代码片段中的 换成 say.. SQLException
,它就可以工作。规范内容如下:
如果类型的联合包含两个备选方案 Di 和 Dj (i ≠ j),则这是编译时错误,其中 Di 是 Dj 的子类型。
我无法理解这背后的原因。当然,我的示例中的 multi-catch 完全是多余的,因为我也可以只捕获一个IOException
。但是让我的代码片段合法有什么害处呢?一种做法一定是有害的,才能成为非法的吗?