Exception Handling in Classes and Code Behind with C #

I am a bit stuck with an asp.net project I am doing! I have a class that is called from the code behind and many of its functions do not have a return type, i.e. Are invalid. How do I handle exceptions? Also, if a function within a class has a return type, such as a dataset, how can one of them return an exception or indicate that an exception has occurred? I added the following code from my class, which is referenced by the code.

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!

thank

+1


source to share


3 answers


Eliminate exceptions if you intend to handle them correctly. If you want to reflect bugs in the UI, catch them in the UI. If you want to process them and try to solve the problem in business logic, then catch them and process them at that point.



By the way, your code is susceptible to SQL injection attacks . Better go something about parameterized queries .

+1


source


You are not returning an exception. You drop them. That's the point of exceptions - you don't want exception handling cluttering up your method signatures!

In your catch clauses, you don't actually do anything to handle exceptions. Then you shouldn't catch them, just let them jump to your code and catch them there - put a try around the method call.



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

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

      

0


source


Cool thanks for the answers ... working with the obout library, so you should try and handle your exception handling functions as well.

0


source







All Articles