When to use Try Catch blocks?

  • Thread starter Thread starter Guest
  • Start date Start date
Use them whenever there's a potential of an exception being thrown to guard
your code and help recover from one or more potentila exceptions.
 
Chrysan,
In addition to CT's comments.

I use Try/Catch when there is something specific that I need to do with the
exception. Otherwise I let my global exception handlers handle the event.
IMHO logging should go in the global exception handler. Too often I've seen
Try/Catch blocks where the exception information is "lost" making it harder
to diagnose problems.

I use Try/Finally blocks significantly more often to ensure that resources
are closed, using the "using" statement in C# simplifies this. We will have
to wait for Whidbey (VS.NET 2005) to get the "Using" statement in VB.NET.


For an unhandled exception:
Depending on the type of application you are creating, .NET has three
different global exception handlers.

For ASP.NET look at:
System.Web.HttpApplication.Error event
Normally placed in your Global.asax file.

For console applications look at:
System.AppDomain.UnhandledException event
Use AddHandler in your Sub Main.

For Windows Forms look at:
System.Windows.Forms.Application.ThreadException event
Use AddHandler in your Sub Main.

Hope this helps
Jay
 
Back
Top