java “Catch 分支是相同的”但是仍然需要我抓住它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25528215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:10:57  来源:igfitidea点击:

'Catch branch is identical' however still requires me to catch it

javatry-catch

提问by Juxhin

Whilst reading through my code I noticed my IDE was listing a warning with the following message:

在阅读我的代码时,我注意到我的 IDE 列出了带有以下消息的警告:

Reports identical catch sections in try blocks under JDK 7. A quickfix is available to collapse the sections into a multi-catch section.

在 JDK 7 下的 try 块中报告相同的 catch 部分。可以使用快速修复将这些部分折叠成一个多捕获部分。

And also specifies that this warning is thrown for JDK 7+

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

The try block is as follows:

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();
}

However when removing (the catch blocks that threw that particular warning):

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

catch (ClassNotFoundException var5) {
    var5.printStackTrace();
} catch (IOException ex){
    ex.printStackTrace();
}

I would still get errors at:

我仍然会在以下位置遇到错误:

ObjectInputStream inputStream = new ObjectInputStream(e);
return (ArrayList)inputStream.readObject();


Am I missing something obvious that I haven't figured out so far?

我是否遗漏了一些到目前为止我还没有弄清楚的明显内容?

回答by Makoto

So, since I'm seeing that same warning in IntelliJ (and I think you're using IntelliJ too), why not let Alt+Enter(or Option+Returnif you rather) show you what it means?

所以,既然我在 IntelliJ 中看到了同样的警告(我认为你也在使用 IntelliJ),为什么不让Alt+ Enter(或者Option+,Return如果你愿意的话)向你展示它的含义?

You can collapse exception branches if they're identical, and with the multi-catch syntax, you'll wind up with one catch statement that does the same thing as your three:

如果它们相同,您可以折叠异常分支,并且使用 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;