Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Return Exception from Function in class

Tags:

c#

exception

I am creating a function createFolding in my class named clsFolding. I am inserting some values in database through this function createFolding. So, I am returning int status_id from function back (1 if ok, 0 if error). I also want to return an exception message from function if there is error (if status_id =0) but I do not know how to return multiple values from my function back. here is my code that I have done in my class clsFolding

public class clsFolding
{
    public static string ConStr = ConfigurationManager.ConnectionStrings["FazalConstructions.Properties.Settings.ConnString"].ConnectionString;
    public static SqlConnection con;
    public static SqlCommand cmd = new SqlCommand();
    public static int status_id;
    public static Exception ex;

    public static int createFolding(int id, string name, int qty, string narration, DateTime dt)
    {
        try
        {
            con = new SqlConnection(ConStr);
            con.Open();
            cmd = new SqlCommand("INSERT INTO tblFolding(FoldingID, Name,Quantity,Narration,DateTime)VALUES(@id, @name, @qty, @narration,@dt)", con);

            cmd.Parameters.AddWithValue("@id", id);
            cmd.Parameters.AddWithValue("@name", name);
            cmd.Parameters.AddWithValue("@qty", qty);
            cmd.Parameters.AddWithValue("@narration", narration);
            cmd.Parameters.AddWithValue("@dt", dt);
            cmd.ExecuteNonQuery();

            status_id = 1;
            return status_id;
        }
        catch (Exception ex)
        {
            status_id = 0;
           return status_id;
        }
        ...
    }
    ...
}

here is my code that I used in my form to get data from class

clsStockManagement.updateStock(
    int.Parse(TransactionID.Text), int.Parse(projectID.Text),
    int.Parse(cbItem.SelectedValue.ToString()),
    int.Parse(tbQty.Text), DateTimee.Value);
if (clsStockManagement.status_id==1)
{
    MessageBox.Show("Process Successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (clsStockManagement.status_id==0)
{
     MessageBox.Show("Process UnSuccessful", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
}
like image 253
Waqas Ali Avatar asked Oct 18 '25 11:10

Waqas Ali


1 Answers

I think you're missing the point of exceptions. You rarely catch them where they're thrown. The point of exceptions is to let them bubble up. Done right, your createFolding() method doesn't need any exception handling or return codes. It simplifies down to this:

public class clsFolding
{
    //no need for this to be public
    private static string ConStr = ConfigurationManager.ConnectionStrings["FazalConstructions.Properties.Settings.ConnString"].ConnectionString;

    public static void createFolding(int id, string name, int qty, string narration, DateTime dt)
    {
         string sql = "INSERT INTO tblFolding(FoldingID, Name,Quantity,Narration,DateTime)VALUES(@id, @name, @qty, @narration,@dt)";

         //fyi: a static SqlConnection reference is a VERY BAD IDEA
         // use a new variable in each method call
         using(var con = new SqlConnection(ConStr))
         using(var cmd = new SqlCommand(sql, con))
         {
             cmd.Parameters.AddWithValue("@id", id);
             cmd.Parameters.AddWithValue("@name", name);
             cmd.Parameters.AddWithValue("@qty", qty);
             cmd.Parameters.AddWithValue("@narration", narration);
             cmd.Parameters.AddWithValue("@dt", dt);

             con.Open();
             cmd.ExecuteNonQuery();
         }
    }
}

I'd also do something about those AddWithValue() calls.

Now you want to show a MessageBox if this fails. That's fine. Do that. It sounds like a good idea. Just do it in the code that calls this method:

try 
{
   clsFolding.createFolding( /* parameters here */);
   MessageBox.Show("Process Successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (SqlException)
{
    MessageBox.Show("Process UnSuccessful, could not write to database", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
}
catch (Exception Ex)
{
    MessageBox.Show("Process UnSuccessful, a non-database error occured", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
}
like image 98
Joel Coehoorn Avatar answered Oct 21 '25 01:10

Joel Coehoorn