what should do when using multiple catch() block & what should
never do for the same?

Answer Posted / auraz

I always try to reduce levels of nesting for readability and maintainability. If you have n try/catch blocks, each handling the same type of exception, why not refactor the code that can throw the exception into methods...it would look something like:

try {
firstBatchOfTricky();
secondBatchOfTricky();
....
nthBatchOfTricky();
} catch (ItWentBoomException e) {
// recover from boom
} catch (ItWentBangException e) {
// recover from bang
}
which is IMHO much more readable than having multiple try/catches. Note that your methods should describe what they do in the spirit of self documenting code.

Since you have your own Exception type, you can add the data you need to the exception to do different things in the catch block. When you say 'more specific message', you can just throw the exception with the detailed message; you shouldn't need multiple catch blocks. If you want to do drastically different things based on the state of the exception, just create more exception types and catch blocks but only one try block, as my pseudocode shows...

Finally, if you can't recover from the exception(s), you should not clutter the code with catch blocks. Throw a runtime exception and let it bubble. (Good advice from @tony in the comments)

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why do you canvas?

616


Why should we use singleton pattern instead of static class?

466


We are seeing so many videos/audios as many web sited. But question is these videos or audios are stored in Databases ( Oracle, Mysql, Sybase,... ) or stored any file directory from there they will give the link for that? Pls explain and give sample code to achieve this one? Thanks, Seenu.

1494


Is integer immutable in java?

552


What is anagram of a string?

523






How do you remove spaces in java?

541


What is the purpose of an interface?

562


design an lru cache in java?

548


What does method mean?

521


Define immutable object?

587


Differences between C and Java?

621


Is string a wrapper class?

519


How do you find the absolute value?

565


Can I extend singleton class in java?

635


what is object slice?

1579