'Catch分支是相同的',但仍需要我抓住它

Jux*_*hin 51 java try-catch

在阅读我的代码时,我注意到我的IDE列出了一条警告,其中包含以下消息:

在JDK 7下的try块中报告相同的catch部分.可以使用quickfix将部分折叠为multi-catch部分.

并且还指定为JDK 7+抛出此警告

try块如下:

try {
    FileInputStream e = new FileInputStream("outings.ser");
    ObjectInputStream inputStream = new ObjectInputStream(e);
    return (ArrayList)inputStream.readObject();
} catch (FileNotFoundException var3) {
    var3.printStackTrace();
} catch (ClassNotFoundException var5) {
    var5.printStackTrace();
} catch (IOException ex){
    ex.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

但是当删除时(抛出该特定警告的catch块):

catch (ClassNotFoundException var5) {
    var5.printStackTrace();
} catch (IOException ex){
    ex.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

我仍会得到错误:

ObjectInputStream inputStream = new ObjectInputStream(e);
return (ArrayList)inputStream.readObject();
Run Code Online (Sandbox Code Playgroud)

我错过了一些我到目前为止还没想到的明显的东西吗?

Mak*_*oto 112

所以,既然我在IntelliJ中看到了同样的警告(我认为你也在使用IntelliJ),那么为什么不让Alt+ Enter(或Option+ Return如果你愿意)告诉你它意味着什么?

如果异常分支相同,你可以将它们折叠起来,并且使用multi-catch语法,你将得到一个与你的三个相同的catch语句:

try {
    FileInputStream e = new FileInputStream("outings.ser");
    ObjectInputStream inputStream = new ObjectInputStream(e);
    return (ArrayList)inputStream.readObject();
} catch (ClassNotFoundException | IOException var3) {
    var3.printStackTrace();
}
return null;
Run Code Online (Sandbox Code Playgroud)

  • 重要的是要注意多捕获中的类型必须是不相交的.+1正确使用多捕获语句. (3认同)