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

时间:2018-02-22 23:49:54

标签: c# exception-handling

我有一个ParsingException类,它在构造函数中占用2个输入。 1.一个字符串消息 2.异常InnerException

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

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

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

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的评论,虽然我回答了被问到的问题但我同意创建“假”例外不一定是最佳做法。我认为这是对other question关于访问自定义IdNumberNONEParsingException作为引发InnerException的{​​{1}}的跟进。

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

InnerExcepion

或者因为try { ... } catch(IdNumberNONEParsingException e) { ... } catch(ParsingException e) { ... } finally { ... } 继承自IdNumberNONEParsingException,所以抓住ParsingException会抓住两者,例如。

ParsingException