首页 > 解决方案 > 如何捕获特定类型的 InvalidOperationException?

问题描述

我今天在我的代码中遇到了一个错误,当我的列表中有重复的标识符时,它会导致引发以下异常:

System.InvalidOperationException: Sequence contains more than one matching element

虽然我知道我可以像这样捕获这个异常:

string id = "foo";
List<string> DirtyList = new List<string>{"foo","bar","xyzzy","foo"};
string result = null;
try{
    result = DirtyList.Single(x=>x.Equals(id));
}
catch( InvalidOperationException e )
{
    Console.WriteLine( e );
    throw;
}

..但这也将捕获所有其他InvalidOperation异常,包括Sequence contains no elementsSequence contains no matching element许多其他异常。

我怎样才能使它只捕获Sequence contains more than one matching element异常?

我只想捕获这个特定的异常消息,因为我想在我的应用程序的日志文件中留下反馈,解释配置的哪一部分是错误的。

标签: c#exceptioninvalidoperationexception

解决方案


推荐阅读