1

I came across a bug in my code today that would cause the following exception to be thrown when I had duplicate identifiers in my list:

System.InvalidOperationException: Sequence contains more than one matching element

While I know I can catch this exception like so:

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

..but this will also catch all other InvalidOperation exceptions, including Sequence contains no elements, Sequence contains no matching element and many others.

How can I make it so that I'm only catching the Sequence contains more than one matching element exception?

I want to only catch this specific exception message because I want to leave feedback in the log file of my application explaining which part of the configuration is wrong.

MMM
  • 307
  • 8
  • 18
  • [Exception filter](https://thomaslevesque.com/2015/06/21/exception-filters-in-c-6/)? – Sinatr Aug 05 '21 at 07:06
  • If you want to filter on the text, simply filter on the text or a few words using multiple `if" or a switch or a dispatch table or exception filter if more convenient. But maybe you can use some [properties such as Data and HResult](https://learn.microsoft.com/dotnet/api/system.invalidoperationException?#Properties) to refine management instead of checking the string message that can be localized... Thus see if these properties indicate different things for different messages. –  Aug 05 '21 at 07:06

0 Answers0