Memi.Reflection

Private members of memi's thoughts

When to use Try...Catch

Sometimes I feel a bit confused about the proper usage of "Try...Catch" blocks. The (healthy?) developer instinct is to put it wherever possible. However, I think that an over-usage of it can lead to an unnecessary cumbersomeness of the code, without a real benefit.

Since most of the applications today have some generic error handling at the application level (eg. at the Application_Error event of the global.asax file, on web apps) which usually writes something to a log and redirects the user to a friendly error page, there is no real need to wrap everything with Try...Catch block.

IMHO, we will need to use it on the following cases:

1. When a special action is required for this specific exception, eg. closing connection to the database.

2. When the original exception should be replaced /  wrapped in another, maybe friendlier, exception.

In any other case, no such block is necessary. The generic handler will take care of it.

What do you think of it? Am I missing something?

Posted: May 13 2004, 07:44 PM by memi | with 4 comment(s)
Filed under:

Comments

Larry Osterman said:

If you're going to use exception handling, you need to wrap every operation that might concievably throw (including arithmetic operations), just like if you were checking for error codes.

Check out Michael Grier's blog for more details (http://weblogs.asp.net/mgrier). I believe that Raymond's (http://weblogs.asp.net/oldnewthing) also written about this.


# May 13, 2004 12:59 PM

laxmi said:

how do u do a global error trapping for a desktop app?
# May 13, 2004 1:04 PM

Dan said:

I would agree with Memi on this one, you must only trap when you can do something usefull(correct the situation, add infos, release ressources, etc.). And please do not obscure exact exception message with a new Throw like "Something wrong happened.".

You could also use global catching. In WebApps, you just code the OnError in Global.asax and in WinForms you do an AddHandler Application.ThreadException. So every exception uncatched by you will end up with full stacktrace in your loggin mecanism.

Btw, i have found countless links and documents about exception handling in managed .NET, so i don't quite understand comments like : "exception handling is one of the least documented aspects of .net programming"

Here's some usefull links with tips about exception :

HTH;

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/exceptdotnet.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag/html/scalenetchapt05.asp
# May 13, 2004 3:27 PM

Dan said:

To laxmi : "...in WinForms you do an AddHandler Application.ThreadException..."
# May 13, 2004 3:30 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)