Skip to content

Feature: more specific exception types from System.Linq.Queryable.Single #122703

@epa

Description

@epa

Description

Currently Single throws an InvalidOperationException when no element was found, and throws an InvalidOperationException when more than one element was found. To tell them apart you'd have to look at the message text. I suggest creating two new exception classes and throwing a different one in the two cases. Since the new exceptions would inherit from InvalidOperationException, I believe this would be fully backward compatible.

Reproduction Steps

Something like this should work

int[] elems = { 1, 2, 3, 4 };
try { elems.Single(x => x % 2 == 0); }
catch (NoElementFoundException) { System.Console.WriteLine("none found"); }
catch (MultipleElementsFoundException) { System.Console.WriteLine("more than one found"); }

At the same time catch (InvalidOperationException) should continue to work as it does now.

Expected behavior

In the above example "more than one found" would be printed as that's the exception type thrown.

Actual behavior

(Currently these two exception types do not exist.)

Regression?

No

Known Workarounds

Currently you can inspect the message text of the exception, but this is messy and fragile.

Configuration

.NET 8

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions