如何在 catch 块外使用 throw 语句传递 InnerException?

How can I pass an InnerException using throw statement outside catch block?

我有一个 ParsingException class,它在构造函数中接受 2 个输入。 1. 字符串消息 2.异常内部异常

public ParsingException(string errorMessage, Exception innerException) : base(errorMessage, innerException)
{

}

如果我按照下面的方式使用,

if (some condition)
{
    throw new ParsingException("NoIdNumber:Length of Id Number is 0",**NEED TO PASS AN INNER EXCEPTION OVER HERE**);
}

我怎样才能做到这一点?

你还需要创建内部异常(如果你没有捕获它,你就不能传递你没有的东西,所以你要么捕获它要么创建它)例如。

if (parsedValue == null)
{
    throw new ParsingException("Parsing failed", new NullReferenceException("Value was null"));
}
else if (parsedValue.Id.Length == 0)
{
    // Assuming you have a custom "NoIdException" exception defined, you can just create a new instance of it and pass that. Otherwise you can create a generic "Exception"
    var noIdException = new NoIdException("No Id was provided"); // Don't throw, just create so we can pass to the ParsingException
    throw new ParsingException("NoIdNumber:Length of Id Number is 0", noIdException);
}

编辑:作为对@Evk 评论的回应,虽然我已经回答了所问的问题,但我同意创建 "fake" 例外不一定是最佳做法。我认为这是对您的 other question 关于访问自定义 IdNumberNONEParsingException 作为抛出的 ParsingExceptionInnerException 的跟进。

我只是想指出,可能有更好的方法来处理这个问题,而不需要弄乱 InnerExcepion,例如,您可以有多个 catch 子句来分别处理任一异常,例如。

try { ... }
catch(IdNumberNONEParsingException e) { ... }
catch(ParsingException e) { ... }
finally { ... }

或者因为 IdNumberNONEParsingException 继承自 ParsingException,捕获 ParsingException 将同时捕获两者,例如

try { ... }
catch(ParsingException e) // Will still catch IdNumberNONEParsingException
{
    if (e is IdNumberNONEParsingException) // Checks if the exception that was thrown was an IdNumberNONEParsingException
    {
        // Special logic for handling IdNumberNONEParsingException
    }
    else
    {
        // Special logic for handling non-IdNumberNONEParsingExceptions
    }
    // Shared logic for handling all types of ParsingExceptions eg. logging, cleanup, etc.
}