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

Juxhin picture Juxhin · Aug 27, 2014 · Viewed 16.2k times · Source

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

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

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

The try block is as follows:

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 (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?

Answer

Makoto picture Makoto · Aug 27, 2014

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+Return if you rather) show you what it means?

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:

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