简体   繁体   English

使用 InnerException 抛出异常 c#

[英]throw Exception with InnerException c#

I'm working on code that store Exception.InnerException to db:我正在处理将Exception.InnerException存储到 db 的代码:

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

What exception (type of exception) should I throw to check my code?我应该抛出什么异常(异常类型)来检查我的代码?

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

This example isn't very clear, an ArgumentException will rarely have an innerexception.这个例子不是很清楚,一个 ArgumentException 很少会有内部异常。 But when you really want to:但是当你真的想要:

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

or maybe或者可能

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

During the handling part, what if there is no InnerException, or the InnerException again has an InnerException?在处理部分,如果没有InnerException,或者InnerException又出现了InnerException怎么办?

What you probably want:你可能想要的:

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

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

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