tags:

views:

74

answers:

2

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?

+6  A: 

NoSuchElementException ?

NullUserException
Is it that obvious? :)
Starkey
Thanks, I was only looking for the exceptions that implement [`Exception`](http://download.oracle.com/javase/6/docs/api/java/lang/Exception.html) Now, when this is implementing `RuntimeException` is it what's called an "unchecked" exception? and is there anything I should think of when using such an exception?
Jonas
Yes, `RuntimeException` s are unchecked. You can read all about it here: [Unchecked Exceptions - The Controversy](http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html)
NullUserException
A: 

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.

Jörg W Mittag