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:
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.
Yes, it is primarily for cleaner code.
That idea is equivalent to the difference between:
if (myVar == true && myOtherVar == false)
// Logic
And
if (myVar == true)
{
if (myOtherVar == false)
// Same logic
}
It's just shorter, cleaner code.
It is for cleaner code .. but that is very valuable. In some cases you can have 4 or 5 exceptions thrown and if all you want to do is the same in all cases, which is often the case, that cuts down a lot of code.
This makes it more readable and also better testable. That in itself is valuable enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With