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

时间:2011-09-16 05:33:17

标签: 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);
}

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

这是我的DatabaseException类。

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

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

在运行程序时,它会在

显示错误
 sqlCommand.ExecuteQuery();

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

任何人都可以帮助我吗?提前致谢。

5 个答案:

答案 0 :(得分: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
  }
}

答案 1 :(得分:0)

SqlCommand属性和方法都没有抛出您创建的DatabaseException。因此,你的捕获永远不会触发。

您创建并调用Exception DatabaseException并不意味着所有“数据库”代码现在都会抛出异常。编写SqlCommand时,编写它是为了抛出一组非常具体的异常。您可以在MSDN上找到SqlCommand及其方法的异常列表。

如果我的回答对您没有意义,请告诉我。

答案 2 :(得分:0)

你自己的异常很好但是Sql.ExecuteQuery会抛出一个SqlException,你可以这样做:

void CallDatabase( /* your parameters */)
{
    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 (SqlException ex)
    {
        throw new DataBaseException("Database error", ex);
    }
}

/* somewhere in your code */
try
{
   CallDatabase(...);
}
catch (DataBaseException ex)
{
    MessageBox.Show(ex.Message);
}

答案 3 :(得分:0)

这就是我写这个例程的方式(或多或少)。确保关闭数据库连接并使用 使用 构造释放 sqlCommand obj:

 try
    {
        string insertData = string.Format("INSERT INTO " + constants.PIZZABROADCASTTABLE + " VALUES(@starttime,@endtime,@lastupdatetime,@applicationname)");
        using (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 (Exception ex)
    {
        string s = "Failed to insert into table " + constants.PIZZABROADCASTTABLE + "Database Error! " + Environment.NewLine + "Details: " + ex.ToString();
        MessageBox.Show(s, MessageBoxButtons.OK, MessageBoxIcons.Error);
        // Or
        //throw new DatabaseException(s, ex);
    }
    finally
    {
        if (databaseConnectivity != null && databaseConnectivity.connection != null) 
            databaseConnectivity.connection.Close();
        else
            MessageBox.Show("No database connectivity!", "Error", MessageBoxButtons.OK, MessageBoxIcons.Error); 
    }

答案 4 :(得分:0)

使用Throw Class,更多信息在这里。

http://msdn.microsoft.com/en-us/library/system.activities.statements.throw.aspx

问候。

相关问题