C:\cs151\chap80>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) C:\cs151\chap80>
The stack trace tells the story:
the user entered rats which
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
nextInt() found the problem it
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
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
But an error is too severe for a program to handle.
Most application programs must stop running.
(Thought question:) Are
Error objects and
Exception objects related?