C:\JavaSource>java Square Enter an integer: rats Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at Square.main(Square.java:12)
The stack trace tells the story:
the user entered rats which Scanner
could
not convert to an integer, so an Exception was thrown.
Nothing is wrong with the program.
The problem is with the data.
nextInt()
cannot convert
"rats" into an int
.
When nextInt()
found the problem it
threw an InputMismatchException
.
The Java run-time system caught the exception,
halted the program, and printed the error messages.
An exception is a problem that occurs when a program is running. Often the problem is external to the program, such as bad user input, or mechanical failure of an I/O device. When an exception occurs, the Java virtual machine creates an object of class Exception which holds information about the problem.
A Java program itself may
catch an exception.
It can then use the Exception
object
to recover from the problem.
An error, also, is a problem that occurs
when a program is running.
An error is represented by an object of class Error
.
An Error
is thrown by the Java Virtual Machine when it encounters an internal problem.
There is little you can do when this happens.
Most application programs must stop running.
(Thought question:) Are Error
objects and
Exception
objects related?