I am looking at the example in How to Program in Java, 7e.
User inputs the data manually into object of class AccountRecord record
AccountRecord record = new AccountRecord();
Scanner input = new Scanner( System.in );
while ( input.hasNext() ) // loop until end-of-file indicator
{
try // output values to file
{
// retrieve data to be output
record.setAccount( input.nextInt() ); // read account number
record.setFirstName( input.next() ); // read first name
record.setLastName( input.next() ); // read last name
record.setBalance( input.nextDouble() ); // read balance
.............................................................
catch ( NoSuchElementException elementException )
{
System.err.println( "Invalid input. Please try again." );
input.nextLine(); // discard input so user can try again
} // end catch
}
I have hard time figuring out how catch ( NoSuchElementException elementException ) works. According to Java Documentation, NoSuchElementException is
Thrown by the nextElement method of an Enumeration to indicate that
there are no more elements in the enumeration.
So, why it would also throw an exception in case type mismatch between expected and what is actually entered, such as for record.setAccount(input.nextInt()), user inputs some text string?
Thanks !
For type mismatch problems, you should catch
InputMismatchException. Since it inherits fromNoSuchElementException, you will catch it by catching aNoSuchElementException(so the code as it is will catch it and work as expected). To me, that’s a strange inheritance relationship, though…. Certainly does not represent anis-arelationship.If you really want to differentiate both cases, catch an
InputMismatchExceptionbefore aNoSuchElementException.