Question

I am creating asp.net web apps in .net 3.5 and I wanted to know when to use and when not to use Try Catch Finally blocks? In particular, a majority of my try catch's are wrapped around executing stored procs and populating textfields or gridviews? Would you use Try Catch EVERYTIME when you execute a stored proc and populated a data display control?

My code block usually looks like:

    protected void AddNewRecord()
    {
        try
        {
           //execute stored proc
           // populate grid view controls or textboxes
        }
        catch (Exception ex)
        {
           //display a messagebox to user that an error has occured
           //return
        }
        finally
        { }
   }
Was it helpful?

Solution

The answer is "it depends".

You might want to use a try{...} catch {...} around every atomic operation so that if there is a problem you can roll back to the last good state (using transactions). This may be one or several stored procedures - it depends on your application.

If you are trapping the exception, make sure you are explicit in which exceptions you catch. You shouldn't have catch (Exception ex) or catch() - known as "catch all" exception handling - but have specific catch statements like catch (IndexOutOfRangeException ex) (for example) instead.

However, if you can't handle the exception or there's nothing you can do to clean up, then you shouldn't trap it.

OTHER TIPS

You should only use try catch, when you intend on handling the exception in the catch block. What I mean by handle is, log the error, choose a different path because of the error etc. If you merely intend on re-throwing it, there is no point in having try catch.

As others have said, it depends. I tend to use try/catch/finally blocks in two situations:

  • I need to handle the Exception in some way other than simply re-throwing it.

  • I need to clean up some resources in the finally block.

Other than those two situations, I let the calling code handle any Exceptions that might happen.

In addition to what others have said, be sure to avoid doing this:

    try
    {
        throw new ApplicationException("Fake sql ex");
    }
    //catch and do nothing.  swallowing exceptions
    catch(Exception){ }                 

Most of the time you should not be catching exceptions. Some places where it does make sense to catch an exception e.g.,

When you can recover from that specific exception. When you need to log it or report it (e.g,. to the user)--usually at the top level in your code. When the caller of your code can not handle exceptions, so you need to convert them into some other error format.

Also, the using block statement can be used to actually call Dispose on IDisposable objects, which removes the need for try...finally.

What is the Exception you are expecting from the stored proc? Providing you don't use pokemon exception handling and know exactly what your application is expected to do, anything that doesn't fit the specific Exception you want to to catch will be caught by the Application object.

In other words don't use catch {} or catch (Exception), but specialized exception handling:

catch(SqlException e)
{
   // Log stacktrace and show a friendly error to your user
}

The Application.Error event is where unexpected behaviour should be caught and is easier to trace than simply having a customer return to you saying "my fields aren't displaying anything".

Use "try catch" within the innermost loop that should keep executing when a particular exception occurs. Be mindful that if you have a loop that executes 10,000 times and an exception occurs on e.g. the tenth repetition which won't affect the other 9,990 it may be useful to catch the exception and let the loop keep going. On the other hand, if the exception indicates a fault that suggests the 11th, 12th, 13th, etc. times through the loop are also going to fail, it would be much faster to let the exception kill the loop than to keep retrying an operation that isn't going to work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top