Reputation: 492
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?
Upvotes: 1
Views: 132
Reputation: 718718
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 ...
Upvotes: 1
Reputation: 183241
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).
Upvotes: 1