简体   繁体   English

区分原始System.Exception和引发新的Exception / ApplicationException?

[英]Distinguish between original System.Exception and throw new Exception/ApplicationException?

I have already solved the question, and I posted. 我已经解决了问题,并发布了。

For the method that mad the call, is it possible to differentiate between the original System.Exception (ie. throw ex; ) and a new Exception (ie. throw new Exception("Specific error", ex); ) or new ApplicationException ? 对于困扰调用的方法,是否可以区分原始的System.Exception(即throw ex; )和新的Exception(即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;
        }
    }
}

Thanks. 谢谢。

You can specify what kind of exception you want to catch (mind the ordering). 您可以指定要捕获的异常类型(注意顺序)。 Exceptions have an InnerException property that may contain additional information that caused the current exception. 异常具有InnerException属性,该属性可能包含导致当前异常的其他信息。

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

Ended up using this: 最终使用了这个:

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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM