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



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

Answer / 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

More Core Java Interview Questions

What is the difference between Trusted and Untrusted Applet ?

2 Answers   IBM,


What is Distributed Application and what is its usage?

2 Answers  


Is java call by reference?

0 Answers  


What is meant by interface?

0 Answers  


What are the 5 types of research methods?

0 Answers  


When we should use serialization?

0 Answers  


What is string in java?

0 Answers  


what is difference between prepare stetement and callable starement with example?

1 Answers   CMC,


what is mean by overriding in which situation we wil use?

5 Answers   Atlas Systems, CSC, DCPL,


Difference between Encapsulation and Abstraction

4 Answers   Fidelity,


Can you run the product development on all operating systems ?

1 Answers  


What does @override mean?

0 Answers  


Categories