Try and Catch multiple times??

Posted by Naimishforu under VB.NET on 3/14/2011 | Points: 10 | Views : 2767 | Status : [Member] [MVP] | Replies : 4
Hi,

Is it a good practice to write Try and Catch block most of the times??

I mean should I write it in my functions, as where as I can apply them??

Is it good or bad??

Thanks,
Naimish
http://dotnetinterview.zxq.net/
http://naimishpandya.blogspot.in/



Responses

Posted by: Mesh_2010 on: 3/14/2011 [Member] Starter | Points: 25

Up
0
Down

Hello Naimishforu,

Put the try-catch where you are sure you won't just swallow the exception. Multiple try-catch blocks in various layers may be OK if you can ensure consistency.

For example, you may put a try-catch in your data access layer to ensure you clean up connections properly. But as you can't do much more there you should probably rethrow the exception.

Moving to business layer, you may put try-catch across multiple database operations which you want to proceed atomically. In this case, may be you should rollback everything or put things in a consistent state, log the exception somewhere. Swallowing or rethrowing should be decided on case by case basis.

Your presentation layer should always catch all exceptions, be it some web application, script running in a browser or some rich client application. You may not be able to understand the exception completely, but at least you can ensure that your application does not die in the face of a user.

Thanks
RameSH sinGH

Naimishforu, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Gsolvers on: 3/14/2011 [Member] Starter | Points: 25

Up
0
Down
Agreed!

Best Regards,

VG
www.TeacherJi.com

Naimishforu, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Karthikanbarasan on: 3/15/2011 [Member] [Moderator] [Microsoft_MVP] [MVP] Silver | Points: 25

Up
0
Down
Actually as per the ms blogs its specified not to use the try and catch block un necessarily. This reduces the performance fo the application rather most of the places try to handle the error seperately.

Thanks
Karthik
www.f5Debug.net

Naimishforu, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Varaprasadm.84 on: 3/15/2011 [Member] Starter | Points: 25

Up
0
Down
Based on the Exception we can catch the exception

Vara Prasad.M

Naimishforu, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response