简体   繁体   中英

What Exception should I throw for “No such Element”?

I am implementing a method that looks up an element in a list. The element should exist in the list. Instead of returning null if the element didn't exist, I would like to throw an Exception , but I'm new to exception handling in Java and I don't know what Exception I should throw in this case.

I think this is a quite general case so I can probably use one Exception that already exist in the Java SE standard library.

What Exception should I throw in this case?

Personally, I don't think this deserves an exception. There are infinitely many elements which are not in the list, so the fact that an element can't be found is hardly exceptional, rather it's pretty normal. I would much prefer some sort of Option or Maybe type as the return type.

I have no idea why such a type is not already provided by the JRE (it seems to me a massive oversight), so, unfortunately, you will have to roll your own. However, you can find plenty examples of Java implementations of the Maybe type and even the Maybe monad on the web. It seems to be a pretty common introductory example for teaching generics, for example.

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