Java Reference
In-Depth Information
When to Throw an Exception
Exceptions should be reserved for situations where a method has an exceptional case and dif-
ferent invocations of the method would handle the exceptional case differently. In this situation,
you would throw an exception in the method definition, not catch the exception in the method,
but list the exception in the
throws
clause for the method. That 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 win-
dowing systems using the Swing libraries (Chapter 17), you will see examples of pro-
gramming where the dominant technique is event-driven programming.
event-driven
programming
firing an
event
Self-Test Exercises
22. What is the output produced by the following program?
public class
Exercise
{
public static void
main(String[] args)
{
try
{
System.out.println("Trying");
sampleMethod(98.6);
System.out.println("Trying after call.");
}
catch
(Exception e)
{
System.out.println("Catching.");
}
System.out.println("End program.");
}
public
static
void
sampleMethod(
double
test)
throws
Exception
{
(continued)