如何在c#中创建自定义异常

bha*_*thi 5 c# exception custom-errors

我想在Windows窗体应用程序中创建自己的异常.我正在尝试将一些数据添加到数据库中.

码:

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);
}
Run Code Online (Sandbox Code Playgroud)

在这里,我创建了自己的例外.这里我给出了标量变量@lastuptime而不是@lastupdatetime捕获SqlException.

这是我的DatabaseException类.

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

    }
    public DataBaseException(string message, Exception innerException)
        : base(message, innerException)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

这里运行程序时显示错误

 sqlCommand.ExecuteQuery();
Run Code Online (Sandbox Code Playgroud)

但它不捕获错误并显示消息框文本.我知道我做错了什么.我不知道我创建自定义异常处理是对还是错.

谁能帮我?提前致谢.

San*_*G B 2

您需要抛出自定义异常,以便调用方法可以捕获它。在您的代码中,程序将从数据库抛出异常,而不是您的自定义异常。

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
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可能需要提供一个接受异常对象的构造函数,以便可以保留内部异常。 (2认同)