0

Does well-known checked version of NoSuchElementException exists in standard Java?

My primary motive is clearly communicating method behaviour and so force developer to handle situation where NoSuchElementException is thrown.

Edit: As answers suggest, NoSuchElementException is Exception, an Error. In my case "Object not found" situation is valid behavior. So with that in mind, I came with another solution, using Optional. It's the most direct way to communicate possibility of returning "Object not found".

  • Why don't you create your own? –  Apr 12 '18 at 14:22
  • The `NoSuchElementException` is a runtime exception because it means **you, the programmer** did something wrong (like calling `next()` without checking `hasNext()`) Checked exceptions are for when there is an error that your program might explicitly have a way to recover from (like prompting for the location of a file when a `FileNotFoundException` has occurred). In this case, if you want a checked exception, you'll need to write your own. – Mark Rotteveel Apr 12 '18 at 14:45

2 Answers2

0

There is no standard direct checked equivalent for this exception.

My primary motive is clearly communicating method behavior ...

The real question what "behavior" you are trying to convey.

  • If you want to convey the complete meaning of NoSuchElementException, then there isn't one by definition. The complete meaning includes the possible contexts where the exceptions will be thrown, and clearly any "alternative" exception won't be thrown by various standard classes that throw NoSuchElementException.

  • But if you just want a roughly equivalent meaning, there are some possible candidates: see Is there a standard java exception class that means "The object was not found"?. Or you could simply define a custom (checked) exception.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

I don't think there is.

That said, you should think twice before throwing a checked exception. The standard usage for checked exceptions is to signal abnormal conditions that are out of the caller's control, such as:

  • trying to open a non-existent file
  • trying to use a failed/dropped network connection

The rationale being that if the caller can prevent the abnormal condition, it shouldn't be forced to handle it.

You can find more info in the classic Effective Java book (the 3rd edition just came out, btw), especially Item 71 ("Avoid unnecessary use of checked exceptions").

Nick Larsen
  • 18,631
  • 6
  • 67
  • 96
Marco
  • 479
  • 4
  • 10