Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom exception in c#

I want to create my own exception in windows form application. I am trying to add some data into the database.

code:

try
{
    string insertData = string.Format("INSERT INTO " + constants.PIZZABROADCASTTABLE + 
      " VALUES(@starttime,@endtime,@lastupdatetime,@applicationname)");
    sqlCommand = new SqlCommand(insertData, databaseConnectivity.connection);
    sqlCommand.Parameters.AddWithValue("@starttime", broadcastStartDateTime);
    sqlCommand.Parameters.AddWithValue("@endtime", broadcastEndDateTime);
    sqlCommand.Parameters.AddWithValue("@lastuptime", currentDateTime);
    sqlCommand.Parameters.AddWithValue("@applicationname", txtApplicationName.Text);
    sqlCommand.ExecuteNonQuery();
}
catch (DataBaseException ex)
{
    MessageBox.Show(ex.Message);
}

Here I have created my own exception. Here I have given scalar variable @lastuptime instead of @lastupdatetime for capturing the SqlException.

Here is my DatabaseException class.

class DataBaseException : Exception
{
    public DataBaseException(string Message)
        : base(Message)
    {

    }
    public DataBaseException(string message, Exception innerException)
        : base(message, innerException)
    {
    }
}

Here while running the program it shows the error at

 sqlCommand.ExecuteQuery();

but it does not capture the error and show the message box text. I know i have done some thing wrong. I don't know whether which I created custom exception handling is right or wrong.

Can any one help me? Thanks in advance.

like image 210
bharathi Avatar asked Nov 05 '22 14:11

bharathi


1 Answers

You need to throw your custom exception so that it can be caught by the calling method. In your code, program will throw exception from the DB and not your custom exception.

void UpdateDatabase()
{
//...
        try 
            { 

            } 
               // Your checks to identify - type of exception
               // ...
              // .net exception
              // Throw your custom exception in the appropriate block - 
              // throw new DatabaseException();
            catch (OutOfMemoryException ex1) 
            { 

            }
            catch (InvalidDataException ex2) 
            { 

            }
            // Generic exception
            catch (Exception ex3) 
            { 
                // throw new DatabaseException();
            } 
//....
}

// Method calling UpdateDatabase need to handle Custom exception
void CallUpdateDatabase()
{
 try
  {
    UpdateDatabase();
  }
  catch(DatabaseException dbEx)
  {
    // Handle your custom exception
  }
}
like image 180
Sandeep G B Avatar answered Nov 14 '22 22:11

Sandeep G B