1

Why is NoSuchElementFoundException a RuntimeException aka unchecked error? i have Unchecked errors are the programmers fault right, so what If the user is inputting a file to be read and it exists but is empty. That's not the programmers fault, so how does that make sense?

3
  • 4
    where did you get the idea that runtime errors or unchecked exceptions are programmers fault? Commented Nov 16, 2013 at 6:58
  • 1
    There are methods to check for the existence of the element before fetching it so in some sense it is the programmers fault. Commented Nov 16, 2013 at 7:00
  • Programmer's fault is only that the proper defensive code is missing. In the context of this question, checking with hasNext() before calling next() is the right way of doing it. Most of the time, you can get away without calling hasNext() (for example if you are doing linear search and the element is found early on) but it sometimes it'll bite you back. Commented Nov 16, 2013 at 7:02

2 Answers 2

1

I think the term "fault" here is a bit misleading.

A checked exception is typically one that the program should catch and handle appropriately, whereas an unchecked exception is typically one that the program should prevent. If a method contains the line throw new NoSuchElementException(), that implies that this line isn't supposed to be reached, and if it is reached, that probably means a bug in some calling method.

In the case of java.util.Scanner, which I guess is what you have in mind, the reason it throws a NoSuchElementException when you call e.g. nextLong() and the file is empty, is that you should have called hasNextLong() to check beforehand whether this is safe. The only reason you wouldn't call hasNextLong() first is if you are really expecting the long to be present (e.g., if you're reading a configuration file that came bundled with your program).

Sign up to request clarification or add additional context in comments.

Comments

1

Why is NoSuchElementFoundException a RuntimeException aka unchecked error?

Because that is the way it was designed!

i have Unchecked errors are the programmers fault right ...

Generally speaking, that is correct. But a more accurate characterization would be that a checked exception is one that you would expect to be able to recover from and/or report to the end user.

... so what If the user is inputting a file to be read and it exists but is empty. That's not the programmers fault, so how does that make sense?

In this case, it is "the programmers fault" because he could (and maybe should) have tested for the condition using a has* method before calling the next* method.

But that's kind of beside the point ...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.