Java Reference
In-Depth Information
accessing the patient's record in some file and dividing the sum of the temperatures by
the number of times the temperature was taken. Now suppose these methods are used
for creating different systems to be used in different situations. What should happen if
the patient's temperature was never taken and so the averaging would involve a division
by zero? In an intensive care unit, this would indicate something is very wrong. So for
this system, when this potential division by zero would occur, an emergency message
should be sent out. However, for a system that is to be used in a less urgent setting, such
as outpatient care or even in some noncritical wards, it might have no significance, and
so a simple note in the patient's record would suffice. In this scenario, the method for
doing the averaging of the temperatures should throw an exception when this division
by zero occurs, list the exception in the throws clause, and let each system handle the
exception case in the way that is appropriate to that system.
When to Throw an Exception
Exceptions should be reserved for situations where a method has an exceptional case
and individual invocations of the method would handle the exceptional case differently.
In this situation, you would throw an exception in the method definition and not catch
the exception in the method, but list it in the throws clause for the method. This
way the programmers who invoke the method can handle the exception differently in
different situations.
Event-Driven Programming
Exception handling is our first example of a programming methodology known as
event-driven programming . With event-driven programming, objects are defined so
that they send events , which are themselves objects, to other objects that handle the
events. Sending the event is called firing the event . In exception handing, the event
objects are the exception objects. They are fired (thrown) by an object when the object
invokes a method that throws the exception. An exception event is sent to a catch
block, where it is handled. Of course, a catch block is not exactly an object, but the
idea is the same. Also, our programs have mixed event-driven programming (exception
handling) with more traditional programming techniques.When we study how you
construct windowing systems using the Swing libraries (Chapter 17), you will see
examples of programming where the dominant technique is event-driven programming.
event-driven
programming
firing an event
Self-Test Exercises
24. What is the output produced by the following program?
public class Exercise
{
public static void main(String[] args)
{
try
 
Search WWH ::




Custom Search