System, but they may not be reproduced for publication



Yüklə 83 Mb.
Pdf görüntüsü
səhifə46/82
tarix19.04.2023
ölçüsü83 Mb.
#106251
1   ...   42   43   44   45   46   47   48   49   ...   82
Java A Beginner’s Guide, Eighth Edition ( PDFDrive )

exceptions. What are they?


A
: Chained exceptions were added to Java by JDK 1.4. The chained exception
feature allows you to specify one exception as the underlying cause of another. For
example, imagine a situation in which a method throws an ArithmeticException
because of an attempt to divide by zero. However, the actual cause of the problem
was that an I/O error occurred, which caused the divisor to be set improperly.
Although the method must certainly throw an ArithmeticException, since that
is the error that occurred, you might also want to let the calling code know that the
underlying cause was an I/O error. Chained exceptions let you handle this, and any
other situation, in which layers of exceptions exist.
To allow chained exceptions, two constructors and two methods were added to
Throwable. The constructors are shown here:
Throwable(Throwable causeExc)
Throwable(String msg, Throwable causeExc)
In the first form, causeExc is the exception that causes the current exception. That
is, causeExc is the underlying reason that an exception occurred. The second form
allows you to specify a description at the same time that you specify a cause
exception. These two constructors have also been added to the Error, Exception,
and RuntimeException classes.
The chained exception methods added to Throwable are getCause( ) and
initCause( ). These methods are shown here:
Throwable getCause( )
Throwable initCause(Throwable causeExc)
The getCause( ) method returns the exception that underlies the current
exception. If there is no underlying exception, null is returned. The initCause( )
method associates causeExc with the invoking exception and returns a reference to
the exception. Thus, you can associate a cause with an exception after the
exception has been created. In general, initCause( ) is used to set a cause for
legacy exception classes that don’t support the two additional constructors
described earlier.
Chained exceptions are not something that every program will need. However, in
cases in which knowledge of an underlying cause is useful, they offer an elegant
solution.


CREATING EXCEPTION SUBCLASSES
Although Java’s built­in exceptions handle most common errors, Java’s exception
handling mechanism is not limited to these errors. In fact, part of the power of Java’s
approach to exceptions is its ability to handle exception types that you create. Through
the use of custom exceptions, you can manage errors that relate specifically to your
application. Creating an exception class is easy. Just define a subclass of Exception
(which is, of course, a subclass of Throwable). Your subclasses don’t need to actually
implement anything—it is their existence in the type system that allows you to use them
as exceptions.
The Exception class does not define any methods of its own. It does, of course, inherit
those methods provided by Throwable. Thus, all exceptions, including those that you
create, have the methods defined by Throwable available to them. Of course, you can
override one or more of these methods in exception subclasses that you create.
Here is an example that creates an exception called NonIntResultException, which
is generated when the result of dividing two integer values produces a result with a
fractional component. NonIntResultException has two fields which hold the integer
values; a constructor; and an override of the toString( ) method, allowing the
description of the exception to be displayed using println( ).


The output from the program is shown here:
Ask the Expert


Q
: When should I use exception handling in a program? When should I
create my own custom exception classes?
A
: Since the Java API makes extensive use of exceptions to report errors, nearly
all real­world programs will make use of exception handling. This is the part of
exception handling that most new Java programmers find easy. It is harder to
decide when and how to use your own custom­made exceptions. In general, errors
can be reported in two ways: return values and exceptions. When is one approach
better than the other? Simply put, in Java, exception handling should be the norm.
Certainly, returning an error code is a valid alternative in some cases, but
exceptions provide a more powerful, structured way to handle errors. They are the
way professional Java programmers handle errors in their code.
Try This 9­1
Adding Exceptions to the Queue Class
In this project, you will create two exception classes that can be used by the queue
classes developed by Project 8­1. They will indicate the queue­full and queue­empty
error conditions. These exceptions can be thrown by the put( ) and get( ) methods,
respectively. For the sake of simplicity, this project will add these exceptions to the
FixedQueue class, but you can easily incorporate them into the other queue classes
from Project 8­1.
1. You will create two files that will hold the queue exception classes. Call the first file
QueueFullException.java and enter into it the following:


A QueueFullException will be generated when an attempt is made to store an item
in an already full queue.
2. Create the second file QueueEmptyException.java and enter into it the
following:
A QueueEmptyException will be generated when an attempt is made to remove an
element from an empty queue.
3. Modify the FixedQueue class so that it throws exceptions when an error occurs, as
shown here. Put it in a file called FixedQueue.java.


Notice that two steps are required to add exceptions to FixedQueue. First, get( ) and
put( ) must have a throws clause added to their declarations. Second, when an error
occurs, these methods throw an exception. Using exceptions allows the calling code to
handle the error in a rational fashion. You might recall that the previous versions
simply reported the error. Throwing an exception is a much better approach.
4. To try the updated FixedQueue class, use the QExcDemo class shown here. Put it
into a file called QExcDemo.java:


5. Since FixedQueue implements the ICharQ interface, which defines the two queue
methods get( ) and put( ), ICharQ will need to be changed to reflect the throws
clause. Here is the updated ICharQ interface. Remember, this must be in a file by
itself called ICharQ.java.


6. Now, compile the updated ICharQ.java file. Then, compile FixedQueue.java,
QueueFullException.java, QueueEmptyException.java, and
QExcDemo.java. Finally, run QExcDemo. You will see the following output:

Yüklə 83 Mb.

Dostları ilə paylaş:
1   ...   42   43   44   45   46   47   48   49   ...   82




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə