使用InnerException C#引发异常

时间:2019-07-10 10:53:40

标签: c# exception

我正在研究将Exception.InnerException存储到数据库的代码:

try
{        
    // what should I throw here?
}
catch (Exception ex)
{
    errorService.Save(ex.InnerException);
}

我应该抛出什么异常(异常类型)来检查代码?

1 个答案:

答案 0 :(得分:3)

throw new ArgumentException(); // what should I throw here?

这个例子不是很清楚,ArgumentException很少有内部异常。但是当您真正想要:

 new ArgumentException("parameter-name", previouseException);

或者也许

new Exception("I'm just a wrapper", new ArgumentException("parameter-name"));

在处理过程中,如果没有InnerException或InnerException再次具有InnerException怎么办?

您可能想要的东西:

catch (Exception ex)
{
    while(ex.InnerException != null)  ex = ex.InnerException;
    errorService.Save(ex);
    // throw; here unless you're very sure about handling everything 
}