将sqlexception抛出到使用常规异常的调用方法?

时间:2016-02-11 21:34:07

标签: c# asp.net tsql .net-4.0 asp.net-4.0

我正在尝试捕获特定的SqlException 515(无法将值NULL插入列中),并且我无法在实际INSERT之前预先检查该值。我只能捕获错误并确定它是什么错误。

在下面的执行中,alert()可以显示这些消息:某处有一个空值(来自SqlException 515)或一般错误,说明出错了。

在这种情况下,我知道我可以创建并抛出自定义异常错误,但我想只使用我在这里提供的内容,因为SqlException将捕获确切的错误。

此外,这两种方法分为两个不同的类,我只想在System.Data.SqlClient方法中包含Insert()

最后,我可以使用常规System.Exceptionsubstring方法并搜索特定字符串。但应该有更好的方法。

所以这是我的伪代码:

public void InsertNewCar()
{
    try
    {
        Car myCar = new Car();
        myCar.Insert();
    }
    catch (Exception ex)
    {
        alert(msg); //Alerts the user: "Something missing" or "generic error"
    }
}

public void Insert()
{
    try
    {
        SqlHelper.ExecuteNonQuery(ConnString, CommandType.Text, sqlInsert);
    }
    catch (SqlException ex)
    {
        if (ex.Number == 515)
        {
            //throw exception specifying that something's missing in the INSERT
        }
        else
        {
            throw ex;  //throw ex that will be interpreted as a generic error.
        }
    }
}

我的问题是:一旦我抓住SqlException 515,我该怎么办呢?丢弃后,我无法检查InsertNewCar()内的错误编号。

我可以让Insert()返回一个值,但不会抛出异常。我不想使用ref关键字。

感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用特定的其他例外重新抛出它:

throw new SomethingMissingException("Some guiding text", ex /*the original exception*/);

通过这种方式,您可以以更通用的方式在其他地方处理它。另外,不要忘记将原始异常添加到您抛出的异常中。它可能会在某个时候派上用场。

相关问题