Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using multiple exceptions in one catch block?

Tags:

java

java-7

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:

  1. only catch IOException because FileNotFoundException is a subtype.
    or
  2. 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.

like image 923
AAaa Avatar asked Aug 25 '11 19:08

AAaa


4 Answers

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.

like image 77
erickson Avatar answered Nov 04 '22 07:11

erickson


Yes, it is primarily for cleaner code.

like image 21
nicholas.hauschild Avatar answered Nov 04 '22 06:11

nicholas.hauschild


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.

like image 1
Jon Martin Avatar answered Nov 04 '22 07:11

Jon Martin


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.

like image 1
Manfred Moser Avatar answered Nov 04 '22 07:11

Manfred Moser