Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use multiple catch blocks?

Tags:

try-catch

We can use multiple catch block in Try-Catch. But my Question is : why to use multiple catch blocks when it can be done by using single catch block?

  1. Suppose I want exact cause of my problem, I can get that by Ex.message

  2. If I want to show customized message to user, I can show it by putting If-Else loop on Ex.Message.

Thanks in advance.

like image 862
LS206 Avatar asked Sep 11 '13 05:09

LS206


1 Answers

To handle the individual exception accordingly.

For example: If your program is handling both database and files. If an SQLException occurs, you have to handle it database manner like closing the dbConnection/reader etc., whereas if a File handling exception then you may handle it differently like file closing, fileNotFound etc.

That is the main reason in my point of view.

For point numbers 1 and 2:

If showing error message is you main idea then you can use if..else. In case if you want to handle the exception then check the above point of my answer. The reason why I stretch the word handling is because it is entirely different from showing a simple error message.

To add some quotes I prefer Best Practices for Handling Exceptions which says

A well-designed set of error handling code blocks can make a program more robust and less prone to crashing because the application handles such errors.

like image 166
Praveen Avatar answered Oct 29 '22 11:10

Praveen