views:

368

answers:

3

Hi...

I'm a little bit stuck with a asp.net project that i'm doing! I have got a class that is called from the code behind and many of its function have no return type ie, being void. How does one do exception handling then??? Also, if the function within the class does have a return type of, for instance, a dataset how would one then return an exception or indicate that an exception had occured? I have attached the following code from my class which is referenced from the code behind.

public void fnRecord(string []varList, string fnName)
    {
        try
        {
            String x;

            StringBuilder SQLParameters = new StringBuilder();

            SQLParameters.AppendLine("SELECT #{Function}(");
            {
                SQLParameters.Replace("#{Function}", fnName);
            }

            for (int i = 0; i < varList.Length; i++)
            {                   
                x = varList[i].ToString();
                SQLParameters.Append("'" + x + "',");
            }

            SQLParameters.Remove((SQLParameters.Length - 1), 1);
            SQLParameters.Append(")");

            string SQLCMD = SQLParameters.ToString();

            conn.Open();
            NpgsqlCommand command = new NpgsqlCommand(SQLCMD, conn);
            Object result = command.ExecuteScalar();
        }

        catch (NpgsqlException ne)
        {
            //return ne;
        }

        catch (Exception x)
        {
            //error code
        }

        finally
        {
            conn.Close();
        }
    }

Any help would be appreciated!

Thanks

+1  A: 

Only catch the exceptions where you intend to handle them properly. If you want to reflect the errors in the UI, catch them at the UI. If you want to handle them and try to deal with the issue in the business logic, then catch them and handle them at that point.

By the way, your code is susceptable to SQL injection attacks. Best go learn something about parameterised queries.

OJ
A: 

You don't return exceptions. You throw them. That's the point of exceptions - you don't want exception handling cluttering your method signatures!

In your catch clauses, you don't actually do anything to handle the exceptions. Then you should not catch them at all, just let them bubble up to your code-behind, and catch them there - put a try-catch round the method call.

Alternatively, catch your SQL exceptions in your method, then throw a new exception with some sensible message, adding the SqlExceptions as the inner exception, like this

catch (NpgsqlException ne)
{
    throw new Exception("Your explanatory message here", ne);
}
finally
{
    ...
}
Tor Haugen
A: 

Cool thanks for the answers... working with the obout library so have to try and work out their exception handling functions too.