-1

I've read It isn't a best practice to handle multiple Exceptions like this:

public void myMethod() throws ExceptionA, ExceptionB, ExceptionC {
    //more code here
}

And then to call myMethod():

try {
    myObject.myMethod();
} catch(Exception e) {
    //More code here
}

Despite Exception is the parent class of all the other exceptions, it is consider a bad practice. But, in my application I'm using java SE 6 and I need to:

  • Do File operations that can imply a FileNotFOundException and IOException
  • Marshal objects (in order to create XML files) JAXBException
  • Create a pdf file (using pdfbox library) COSVisitorException
  • Send an email using JavaMail, MessagingException

The easiest way is to add a throws statement in method declaration, but what could be the proper way to write the client method?

Is it OK to add 6 or 7 catch blocks to handle all the possible exceptions?

MFB
  • 19,017
  • 27
  • 72
  • 118
Mario Rodz
  • 37
  • 1
  • 8

1 Answers1

2

Generally speaking (for Java 6 and below), you should handle each exception individually...

try {
    myObject.myMethod();
} catch (ExceptionA e) {
    // Condition for A
} catch (ExceptionB e) {
    // Condition for B
} catch (ExceptionC e) {
    // Condition for C
}

This allows you to handle each exception differently based on what it is, but also means you are only handling those exceptions reported to be thrown by the method

In Java 7+ you can make use of "multi-catch" or "combined catch" (we can't find an "official" term)

try {
    myObject.myMethod();
} catch (ExceptionA | ExceptionB | ExceptionC e) {
    // Condition for A and B and C
}

But even then, you should be focusing exceptions into "common" use groups

try {
    myObject.myMethod();
} catch (ExceptionA | ExceptionB e) {
    // Condition for A and B
} catch (ExceptionC e) {
    // Condition for C
}

Another option, if you control how the exceptions are defined, is to extend from a common base exception, a good example of this is the FileNotFoundException which extends from the IOException, which is thrown by FileReader and FileInputStream (as examples), this means you can handle the FileNotFoundException as a common IOException should you wish...

FileReader fr = null;
try {
    fr = new FileReader(new File(...));
    // Read from reader...
} catch (IOException exp) {
    // Common catch block
} finally {
    // Best attempt to close
    try {
        fr.close();
    } catch (Exception exp) {
    }
}

Or you could handle the FileNotFoundException as it's own condition...

FileReader fr = null;
try {
    fr = new FileReader(new File(...));
    // Read from reader...
} catch (FileNotFoundException exp) {
    // File not found condition
} catch (IOException exp) {
    // Other IO condition
} finally {
    // Best attempt to close
    try {
        if (fr != null) {
            fr.close();
        }
    } catch (Exception exp) {
    }
}

This allows you to either group "like" exceptions together, but also provides you with the control to define more fine grained conditions should you need to...

Beware though, we the above example, if I put the IOException first, the FileNotFoundException would never be handled, when doing this, make sure that you use the lowest/tightest/finest exceptions first, as they are processed sequentially in the order you have listed

Another option (which I'm not keen on, but have seen) might be to catch a "common" ancestor and then compare the actual type, which would allow you to provide common handlers for some sub-type of the exception.

} catch (IOException exp) {
    if (exp instanceof FileNotFound || exp instanceof FileSystemException) {   
        // Common handling
    } else {
        // Generic handling
    }
}

This might be helpful in situations where the method only throws the ancestor type (ie IOException), but you need to provide a more fine grained resolution

But, again, I would be focused on only handling the expected "common" exceptions declared as been thrown, don't be tempered to catch Throwable for example

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • 1
    I've never heard the combined catch clause called a "multiple catch block" before, and I'd say that name is easily confused with the term "multiple catch blocks" meaning plural catch blocks. Is there really no better name for it? I've always known it to be a combined-catch block. I realize this discrepancy in naming after responding to you in the comments. – FThompson May 08 '15 at 00:40
  • I usually refer to them as a "multi-catch", but calling them "multiple-catch blocks" can very well cause confusion with "multiple catch-blocks", yes. – Raniz May 08 '15 at 00:42
  • 1
    @Raniz The hyphen is crucial in distinguishing the two, I'd say. "Multi-catch" is clear to me. – FThompson May 08 '15 at 00:43
  • So, there is no a maximum number of exceptions handled in a method?? And, what about DRY principle in every catch condition? – Mario Rodz May 08 '15 at 00:43
  • @MarioRodz There's likely a theoretical max of 255 (or some other large number you'll never hit), but I wouldn't worry about the actual max. – FThompson May 08 '15 at 00:44
  • Additional to @MadProgrammer this catch blocks work in sequentially. When you try to catch multiple exception you need to worry about the order. For example if you catch an java.lang.Exception in the first catch block then other catch block may never hit. – Eranda May 08 '15 at 00:44
  • @Vulcan I think it's semantics IMHO, but that doesn't make it wrong – MadProgrammer May 08 '15 at 00:45
  • @Eranda Yep, while I didn't say it explicitly, I did show it in the last example ;) – MadProgrammer May 08 '15 at 00:47
  • @Vulcan I've tried searching for offical examples by Oracle to see if I can track down a "common" name, the only thing I can come across is ["catching multiple exception ... with improved type checking"](http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html) or simular – MadProgrammer May 08 '15 at 00:55
  • @MadProgrammer I've actually been doing the same, and no specific term is given even through the JRE7 feature list or anywhere else as far as I've found. I'm considering asking about it in a question, but I'm concerned it may be considered too opinion-based simply due to the seeming lack of an official name. – FThompson May 08 '15 at 00:57
  • @Vulcan I think "multi-catch" or "multicatch" are the more "common" terms I'm seeing, maybe your right "combined catch" would be more suitable then "multi" as you can catch "multiple" exceptions using the old style – MadProgrammer May 08 '15 at 01:01
  • 1
    @MadProgrammer It seems "multi-catch" is the official term [provided by Eclipse](http://www.eclipse.org/jdt/ui/r3_8/Java7news/whats-new-java-7.html) (although I still quite like "combined catch"!). And there's a [multi-catch](http://stackoverflow.com/questions/tagged/multi-catch) tag as well. – FThompson May 08 '15 at 01:08
  • @MadProgrammer I've asked [a question](http://stackoverflow.com/q/30114234/1247781) just in case there's someone out there who knows of an official name, but I'm not sure how fruitful of answers I'll get (and may delete the question if it goes nowhere). – FThompson May 08 '15 at 01:14