Java Reference
In-Depth Information
Exceptions
Exceptions are “thrown” by the JVM when a problem is encountered during execution of a Java application. Again,
there can be many reasons for a “run time” exception: user error, system error, security violation, network problems,
and so on. The JVM tries to identify the problem and puts this information in an Exception object. The Exception
object contains information such as the type of exception that was encountered, an error message, and the stack
trace . When a problem is encountered, the JVM's standard procedure is to display the Exception object and end the
application.
You have seen what this looks like. (See the console pane in Figure 7-1 at the end of the next tutorial if you
need a reminder.) How do you think a user would react to receiving these types of messages? This is why it is a good
programming practice to anticipate what errors may occur (i.e., what exceptions may be thrown) and stop the JVM
from responding (i.e., catch the exception within the application program). Once the ugly JVM message is stopped
from being displayed (i.e., the application catches the exception), the application should either resolve the problem or
display a user-friendly message with information so that the user can resolve the problem.
Tutorial: Exceptions
Let's look at exceptions:
1.
In Tutorials/src, create a new package called c7.
2.
Copy all of the following classes from c6 to c7:
AppOptions Employee EmployeeApp
EmployeeFrame EnterEmpInfo ExitButton
TNT TNTButton UsefulFrame
3.
Run c7.TNT as an application.
4.
Select Employee Application
5. Enter “$9.50” (including the $ in the text field) for Hourly Pay Rate, “six” for Exemptions,
and click the Gross button.
The result should look like Figure 7-1 . The text in the console pane is the JVM's printout of the Exception
object. Notice that the first line contains a general error message that identifies the type of exception
( NumberFormatException ) and the offending piece of input ($9.50). The remaining lines show the stack trace . Most
of the stack trace is unintelligible because you don't know how the supplied classes ( Frame , String , Double , etc.)
work internally. For example, the Double class's parseDouble method creates objects and invokes methods of which
you are blissfully unaware. The second line in the console pane shows that the readJavaFormatString method in the
FloatingDecimal class (of which you know nothing) was actually where the error occurred.
 
Search WWH ::




Custom Search