【问题标题】:Distinguish between original System.Exception and throw new Exception/ApplicationException?区分原始 System.Exception 和抛出新的 Exception/ApplicationException?
【发布时间】:2016-02-12 13:44:27
【问题描述】:

我已经解决了这个问题,我发布了。

对于使调用疯狂的方法,是否可以区分原始 System.Exception(即throw ex;)和新的异常(即throw new Exception("Specific error", ex);)或新的ApplicationException

public void InsertNewCar()
{
    try
    {
        Car myCar = new Car();
        myCar.Insert();
    }
    catch (Exception ex)
    {
    if ( /* This ex is the New Exception */
        alert(somethingMissingMsg);
    }
    else /* This is the original exception */
    {
        alert(Something wrong generic error);
    }
}

public void Insert()
{
    try
    {
        SqlHelper.ExecuteNonQuery(ConnString, CommandType.Text, sqlInsert);
    }
    catch (SqlException ex)
    {
        if (ex.Number == 515)
        {
            throw new Exception("Missing something", ex);
            //throw new ApplicationException("Missing something", ex);
        }
        else
        {
            throw ex;
        }
    }
}

谢谢。

【问题讨论】:

  • @Stephen,这不是重复的。订购 catch 块如何与此相关?我的问题与实际异常无关,而是如何区分接收异常的方法中的异常。
  • 我刚刚明白了你的问题......在阅读了对另一个答案的评论......

标签: c# .net exception-handling


【解决方案1】:

您可以指定要捕获的异常类型(注意顺序)。异常有一个InnerException 属性,其中可能包含导致当前异常的附加信息。

try
{
    MethodThatBlowsUp();
}
catch (ApplicationException appex)
{
    //handle 
}
catch (Exception ex)
{
    //handle
}

【讨论】:

  • 谢谢,但我的问题与实际异常无关,而是如何区分接收异常的方法中的异常。
【解决方案2】:

最终使用了这个:

public void InsertNewCar()
{
    try
    {
        Car myCar = new Car();
        myCar.Insert();
    }
    catch (Exception ex)
    {
    if (ex is ApplicationException)
        alert("Something missing Msg");
    else /* This is the original exception */
        alert("Something wrong generic error");
}

public void Insert()
{
    try
    {
        SqlHelper.ExecuteNonQuery(ConnString, CommandType.Text, sqlInsert);
    }
    catch (SqlException ex)
    {
        if (ex.Number == 515)
        {
            throw new ApplicationException("Missing something", ex);
        }
        else
        {
            throw ex;
        }
    }
}

【讨论】:

  • 如果你想重新抛出一个异常,你可能想使用throw,而不是throw ex,并使用多个特定的catch块来捕获你的异常:只对你的情况使用catch (Exception ex)不要期待
猜你喜欢
  • 2012-06-12
  • 2011-07-28
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多