We’ve all heard that in Java 7 we can write:
try {
//something with files and IO
} catch (FileNotFoundException | IOException ex) {
ex.printStackTrace();
System.out.println("It's can't copy file");
}
instead of
try {
//something with files and IO
} catch (FileNotFoundException wx) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
but, what is it really good for besides shorter code?
Even if we want the same operations done in each catch block, we can:
- only catch IOException because FileNotFoundException is a subtype.
or - if one exception is not a subtype of the other one, we can write some handleException() method and call it in each catch block.
So, is this feature only used for cleaner code or for anything else?
Thanks.
It’s not for making code look cleaner and saving key strokes. Those are fringe benefits.
Repetition leads to inconsistency and errors. So, by creating a syntax that makes repetition unnecessary, real errors can be avoided. That’s the motivation behind DRY—not pretty code that is quicker to write.