Try, Try Again

Posted by AgileCoder on May 22, 2008

Originally posted on my old Geekcyclist blog

As I detailed in a post a while ago, I find myself reviewing and updating a large amount of vb.net code that was written by a developer in our shop that moved on to greener pastures. Even though my background was originally in the BASIC world, I moved to C# when Visual Studio .Net 2002 was released and find that I really prefer it to vb.net. I have embraced the curly brace. So I have been converting as much as I can to utility classes in C#.

One of the great improvements of the .Net framework for VB was the Try-Catch-Finally style of error handling. However, just like GOTO, it can be misused and abused. The Pragmatic Programmer tip #34 is Use Exceptions for Exceptional Problems, and is an excellent read. But before you get there, you must have a basic understanding of how an exception is going to be handled.

With a few modifications (including translation to C#), this is a function that was in one of the projects I inherited.

public bool CheckStatus()
{
    try
    {
        SystemCheck();
    }
    catch(Exception)
    {
        SystemCheck();
    }
}

Trust me, it is unlikely that if SystemCheck() threw an exception the first time you called it that it will execute successfully when called again in the catch.

Here is another example:

public DataTable GetData()
{
    try
    {
        DataTable dt = new DataTable();
        /* Code here that:
        Built Command and Connection objects
        Adapter
        Filled Adapter
        */
    }
    catch(Exception)
    {
        //Do Nothing
    }
    finally
    {
        cn.Close();
        //more stuff snipped here
    }
    return dt;
}

The ‘Do Nothing’ has to be a HUGE red flag that there is something wrong.

If you know it might happen, handle it in the body of the function. Save the catch for things that are truly ‘exceptional’. When they happen, log the details, recover if you can, or fail gracefully.



viagra wirkung viagra wirkstoff viagra naturel viagra homme viagra pour homme viagra alkohol viagra dosering viagra precio viagra precio en farmacia viagra masculina viagra effetti collaterali viagra generico viagra generico prezzo