📄 ch3.htm
字号:
reacts by calling <TT>mouseDown()</TT>.If this is overridden by the object in question, its version ofthe method will be called. Like <TT>handleEvent()</TT>,the return value of the helper methods indicate whether the eventhas been completely handled.<P>Table 3.2 lists the available Event helper methods, which areall part of the definition of the Component class.<BR><P><CENTER><B>Table 3.2. Event helper methods.</B></CENTER><P><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=134><I>Method</I></TD><TD WIDTH=325><I>Description</I></TD></TR><TR VALIGN=TOP><TD WIDTH=134><TT>mouseEnter</TT></TD><TD WIDTH=325>Mouse enters the Component's area</TD></TR><TR VALIGN=TOP><TD WIDTH=134><TT>mouseExit</TT></TD><TD WIDTH=325>Mouse leaves the Component's area</TD></TR><TR VALIGN=TOP><TD WIDTH=134><TT>mouseMove</TT></TD><TD WIDTH=325>Mouse has moved</TD></TR><TR VALIGN=TOP><TD WIDTH=134><TT>mouseDown</TT></TD><TD WIDTH=325>Mouse has been pressed down</TD></TR><TR VALIGN=TOP><TD WIDTH=134><TT>mouseDrag</TT></TD><TD WIDTH=325>Mouse has moved while it is pressed down</TD></TR><TR VALIGN=TOP><TD WIDTH=134><TT>mouseUp</TT></TD><TD WIDTH=325>Mouse click has been released</TD></TR><TR VALIGN=TOP><TD WIDTH=134><TT>keyDown</TT></TD><TD WIDTH=325>Keyboard character has been pressed</TD></TR><TR VALIGN=TOP><TD WIDTH=134><TT>keyUp</TT></TD><TD WIDTH=325>Keyboard character has been released</TD></TR><TR VALIGN=TOP><TD WIDTH=134><TT>action</TT></TD><TD WIDTH=325>An action has occurred to the Component</TD></TR><TR VALIGN=TOP><TD WIDTH=134><TT>gotFocus</TT></TD><TD WIDTH=325>The input focus has been placed on the Component</TD></TR><TR VALIGN=TOP><TD WIDTH=134><TT>lostFocus</TT></TD><TD WIDTH=325>The Component has lost input focus</TD></TR></TABLE></CENTER><H2><A NAME="ExceptionClasses"><FONT SIZE=5 COLOR=#FF0000>ExceptionClasses</FONT></A></H2><P>Although the basics of exception handling were discussed in thefirst part of the book, there is a lot more to managing exceptionsin Java than just the "try-catch" clause. The classof exceptions that is thrown and what information can be gleanedfrom the thrown object are also important topics. This part ofexception handling is related to Java's exception class hierarchy,the subject of this section.<H3><A NAME="TheThrowableClass">The Throwable Class</A></H3><P>All throwable objects in Java are an instance of, or are subclassedfrom, the Throwable class, which encapsulates the behaviors foundin all the throwable classes that are part of the Java API. Onewidely used method of Throwable is <TT>getMethod()</TT>.This prints out a detail message attached to the thrown object.The detail message will give extra information regarding the natureof the error. If the default constructor of the thrown objectis used, a system-generated detail message will be provided. Ifyou want a custom message, on the other hand, an alternative constructorcan be used.<P>A couple of examples will illustrate using detail messages. Supposean operation is performed that results in an error. The followingcode will catch the thrown object and print out the detail message:<BLOCKQUOTE><TT>try {<BR> // … do something that causes an exception, suchas <BR>divide by zero<BR>}<BR>catch (Throwable t) {<BR> // Print out the detail message of the error…<BR> System.out.println(t.getMessage());<BR>}</TT></BLOCKQUOTE><P>In another case, suppose that the same code wants to rethrow themessage with its own custom detail message if there is an error.The other constructor for Throwable can be used in this situationto construct the custom message:<BLOCKQUOTE><TT>try {<BR> // … do something that causes an exception, suchas <BR>divide by zero<BR>}<BR>catch (Throwable t) {<BR> // Throw a new Throwable object with<BR> // Custom detail message…<BR> throw new Throwable("This method threw an <BR>exception");<BR>}</TT></BLOCKQUOTE><P>When the new Throwable is caught and <TT>getMessage()</TT>is invoked, the program will get the String <TT>"Thismethod threw an exception"</TT> instead of a system-generatedmessage.<P>Other methods in Throwable can be used for getting the state ofthe runtime stack when the error occurred. The <TT>printStackTrace()</TT>method, for example, prints to standard error the kind of stackoutput that you often see when a Java program terminates abnormally.<H3><A NAME="ExceptionClassHierarchy">Exception Class Hierarchy</A></H3><P>All the other exception classes in the Java API behave similarlyto the Throwable class. They differ only in how they are locatedin the hierarchy of class exceptions. Java divides errors intotwo general groupings, indicated by two parent classes derivedfrom Throwable. The Exception class represents the kind of errorsthat occur in a normal programming environment, such as file notfound, array index out of bounds, null pointers, divide by zero,and so forth. These are "soft" errors, the type of difficultythat a program should be able to easily recover from. In general,Exception classes represent errors that are meant to be caughtby the calling method whenever they occur. Classes derived fromthe Error class, on the other hand, represent more serious errorsthat can occur at unpredictable times and are often fatal in nature.An extreme case of such an Error is a failure within the Javavirtual machine. If this occurs, often the best you can hope foris an orderly shutdown of the program. Because of their unpredictableand catastrophic nature, Error objects do not have to be caughtin exception handlers. In general, programs will be written tocatch only classes derived from the Exception class.<BR><P><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>Note</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>From a terminological standpoint, "exception" (lowercase) is used to refer to all classes of thrown objects. The term "error" (lowercase also) refers to the circumstances that cause the object to be thrown.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>As mentioned in the first part of this book, a method establishesthat it throws an Exception that has to be caught in its declaration.For example, this is the constructor for the class that opensa file for output:<BLOCKQUOTE><TT>public FileOutputStream(String name)throws IOException</TT></BLOCKQUOTE><P>This declaration means that an instance of IOException is thrownwhenever the file specified in the String cannot be opened. TheIOException class is derived from Exception, so any code thatuses this FileOutputStream constructor must catch this exception.This means that code using this constructor must be generallystructured as follows:<BLOCKQUOTE><TT>try {<BR> FileOutputStream fo = new FileOutputStream("MyFile");<BR> // … write the file…<BR>{<BR>catch (IOException e) {<BR> // …Handle the file open problem…<BR>}</TT></BLOCKQUOTE><P>With one notable exception, all methods that throw objects oftype Exception must be called in an exception handler that catchesthe Exception. However, Java provides a branch of Exceptions ofthrown objects that do not have to be caught. These are derivedfrom the RuntimeException class. Subclasses of the RuntimeExceptionclass are those problems that would be too cumbersome to trapevery time they may occur. For example, all accesses to arrayscould result in an exception because the index into the arraycould be bad. However, it would be unwieldy to put an exceptionhandler around all array calls. There would also be a performancehit. Even worse are instances of the NullPointerException classbeing thrown, which theoretically could occur anywhere in theprogram.<P>Just because an exception is a subclass of RuntimeException, however,doesn't mean that a good program should not trap for the thrownobject. For example, the ArithmeticException usually indicatesa divide by zero error. It is good programming to trap for thiserror whenever it occurs. In most cases, division doesn't oftenoccur in a program. Consequently, a clause like the followingis appropriate for many division operations:<BLOCKQUOTE><TT>try {<BR> result = divider / divisor;<BR>}<BR>catch (ArithmeticException e) {<BR> System.out.println("Divide by zero error!");<BR> result = 0;<BR>}</TT></BLOCKQUOTE><P>On the other hand, it is acceptable to have a divide operationthat is not part of an exception handler, since ArithmeticExceptionis a subclass of RuntimeException. Here is a list of the subclassesof RuntimeException:<BR><P><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=481><I>The Subclasses of RuntimeException</I></TD></TR><TR VALIGN=TOP><TD WIDTH=481><BLOCKQUOTE>ArithmeticException<BR>ArrayIndexOutOfBoundsException<BR>ArrayStoreException<BR>ClassCastException<BR>IllegalArgumentException<BR>IllegalMonitorStateException<BR>IllegalThreadStateException<BR>IndexOutOfBoundsException<BR>NegativeArraySizeException</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H3><A NAME="ExceptionHandlersandThrowableClasses">Exception Handlersand Throwable Classes</A></H3><P>The Exception class hierarchy serves a more fundamental purposein Java programming than just providing a way to order exceptionclasses; it plays an important role in determining how an exceptionis handled. When an exception is thrown, Java looks for an exceptionhandler to catch the thrown object. It first looks in the methodwhere the error occurred, checking to see whether it has an appropriateexception handler-one that is the class or a superclass of theexception thrown. Recall that an exception handler can have multiplecatch statements. The catch statements should be ordered in sucha way that a subclass is listed before any of its superclasses.Here is a possible exception handler for managing a variety ofproblems:<BLOCKQUOTE><TT>try {<BR> // … some bad arithmetic operation<BR> // … or maybe a bad array access<BR> // … or a null errror</TT></BLOCKQUOTE><BLOCKQUOTE><TT>}<BR>catch (ArithmeticException e) {<BR> // Handle the exception…<BR></TT></BLOCKQUOTE><BLOCKQUOTE><TT>}<BR>catch (RuntimeException e) {<BR> // Handle the runtime exception…<BR>}</TT></BLOCKQUOTE><BLOCKQUOTE><TT>catch (Exception e) {<BR> // Handle the Exception…<BR>}<BR>catch (Throwable e) {<BR> // Handle the thrown object…<BR>}</TT></BLOCKQUOTE><P>Recall that ArithmeticException is a subclass of RuntimeException.The latter is derived from Exception, which in turn is a subclassof Throwable. In this example, a divide by zero error throws anArithmeticException, which is handled in the first catch statement.On the other hand, a NullPointerException or a bad array accesswill result in a RuntimeException object being thrown, which ishandled in the second catch statement. A serious problem of classError will not be handled until it reaches the last catch statement,which will catch the thrown object since Error is a subclass ofThrowable. This example illustrates that the exception class hierarchyis a critical part of Java's strategy for resolving exceptions.<P>If the method that caused an object to be thrown does not havean appropriate exception handler, the object percolates up thecall stack, and this process of finding an appropriate handleris repeated. If it reaches the top of the stack and no appropriatehandler is found, the program will terminate abnormally.<H3><A NAME="WritingCustomExceptionHandlers">Writing Custom ExceptionHandlers</A></H3><P>It's easy to write your own exception handler. A class is simplycreated that extends the class that should function as the superclass.If a new IOException handler is needed, for example, it couldbe written as the following:<BLOCKQUOTE><TT>public class CustomIOException extendsIOException { }</TT></BLOCKQUOTE><P>The hard part, however, is deciding what the superclass of thehandler should be. In general, it should not be a subclass ofError since these are reserved for "hard" system problems.Using RuntimeException should also be discouraged because of aninteresting controversy over whether there should even be sucha thing as a RuntimeException class. This is because, in someways, the use of RuntimeException classes defeats some of thegoals of exception handling. By definition, a RuntimeExceptionobject does not have to be caught, but this would then increasethe likelihood of an exception not being caught at all, forcingthe program to terminate abnormally. This defeats a key goal ofexception handling, which is to have a graceful resolution ofproblems. Thus, the use of RuntimeException is reserved for classesof errors that would occur too frequently to have an exceptionhandler every time the pertinent methods are called.<P>This leaves the subclasses of Exception as the best candidatefor being the superclass of new exception classes. Some good examplescan be found in the organization of the exceptions in the JavaIO package. One of the c
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -