简体   繁体   中英

Is there a C# equivalent for Java's NoSuchElementException?

Java的NoSuchElementException是否具有C#等效项?

.NET usually uses InvalidOperationException for that. You should not catch NoSuchElementException anyway because it usually indicates a program bug. For that reason the concrete exception type does not matter that much in this use case.

Unfortunately, InvalidOperationException is used in many places for many different things. You often can't tell much from it. This is a flaw in the BCL's exception hierarchy.

In Java, NoSuchElementException is used to indicate that the end of an enumeration has been reached:

Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

The .NET Framework uses a different interface, where IEnumerator.MoveNext would return false , rather than throwing an exception, when the end of an enumeration is reached:

If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false . When the enumerator is at this position, subsequent calls to MoveNext also return false .

Edit : Rawling correctly points out that issues might still arise if the Current property is accessed beyond the end of the collection. In such cases, the behaviour is not consistent. IEnumerator.Current states that an exception will be thrown; however, List<T>.Enumerator.Current states that the behaviour is undefined:

For better performance, this property does not throw an exception if the enumerator is positioned before the first element or after the last element. The value of the property is undefined.

Edit 2 : It appears that there isn't an equivalent exception. In .NET, you must not ignore the state of the enumerator (as identified, for example, through the return value of the MoveNext method), or you will run into undefined behaviour which could unpredictably break your application.

Linq uses:

[InvalidOperationException]

With the message:

Sequence contains no elements 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM