Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

try-catch

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?

like image 922
Juxhin Avatar asked Aug 27 '14 13:08

Juxhin


1 Answers

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;
like image 70
Makoto Avatar answered Nov 14 '22 22:11

Makoto