Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...

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

What is the benefit of lambda expressions?

1070


What is string in java?

1022


whar are the draw backs of programming lang step by step in Clang and next in C++ and next and in Java nad in .Net

2118


Give any two differences between C++ and java.

1155


How many arguments can be passed to main ()?

999


What is fail fast in java?

1174


What is difference between wait and notify in java?

1149


What is the tradeoff between using an unordered array versus an ordered array?

1245


What is the transient keyword?

2193


How is java created?

951


What do you mean by Function Overloading in java?

1186


What is a method vs function?

1051


How does hashset works in java?

1099


What is hashset in java?

1154


What are synchronized blocks in java?

1193