【问题标题】:Throw sqlexception to calling method that uses regular exception?向使用常规异常的调用方法抛出 sqlexception?
【发布时间】:2016-02-11 21:34:06
【问题描述】:

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

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

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

另外,这两个方法位于两个不同的类中,我只想在 Insert() 方法所在的位置包含 System.Data.SqlClient

最后,我可以使用常规的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.
        }
    }
}

我的问题是:一旦我捕获了SqlException515,我能用它做什么?一旦我抛出它,我就无法检查InsertNewCar() 中的错误号。

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

谢谢。

【问题讨论】:

  • “一旦我抛出它,我就无法检查 InsertNewCar() 中的错误号” - 如果你在 InsertNewCar 中捕获 SqlException,你可以... 或者你可以抛出不同类型的异常并在InsertNewCar 中捕获那个
  • 但是所有与 sql 相关的东西都在 Insert() 所在的类中。我不想为此添加 System.Data.SqlClient 命名空间。但我想也可以这样。
  • 对,所以根据我评论的第二部分抛出一个不同的异常......
  • 请注意,您的 sql 异常仍然会被 InsertNewCar 捕获,只要它从您的 Insert 捕获中重新抛出 - SQL 异常继承自异常。您能否更具体地说明“我只想在 Insert() 方法所在的位置包含 System.Data.SqlClient”的意思?
  • 是的,抛出一个不同的异常是要走的路。

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


【解决方案1】:

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

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

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

【讨论】:

  • 我也在考虑这个,但我使用的是System.ExceptionSqlClient.SqlException,所以我认为这两个就足够了。
  • 好吧,如果你不想处理InsertNewCar 中的SqlException,你必须做点什么。而且使用消息代码不是您想要的......
猜你喜欢
  • 2013-01-01
  • 1970-01-01
  • 2012-11-22
  • 2017-05-31
  • 2011-10-22
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多