Java Reference
In-Depth Information
How It Works
All we need to add is the catch block for the new exception. We need to make sure that the index
value for the divisor stored in the exception object is positive so that another exception is not thrown
when we fix up the array. As we arbitrarily set the array element that contained the zero divisor to 1, it
makes sense to set the array element holding the result to the same as the dividend. We can then let the
method main() stagger on.
A point to bear in mind is that the last two statements in the try block will not have
been executed. After the catch block has been executed, the method continues with
the code following the try-catch block set. In practice you would need to consider
whether to ignore this. One possibility is to put the whole of the try-catch block
code in main() in a loop that would normally only run one iteration, but where this
could be altered to run additional iterations by setting a flag in the catch block.
This is a rather artificial example - so what sort of circumstances could justify this kind of fixing up of
the data in a program? If the data originated through some kind of instrumentation measuring physical
parameters such as temperatures or pressures, the data may contain spurious zero values from time to
time. Rather than abandon the whole calculation you might well want to amend these as they occurred,
and press on to process the rest of the data.
Summary
In this chapter you have learned what exceptions are and how to deal with them in your programs. You
should make sure that you consider exception handling as an integral part of developing your Java
programs. The robustness of your program code depends on how effectively you deal with exceptions
that can be thrown within it.
The important concepts we have explored in this chapter are:
Exceptions identify errors that arise in your program.
Exceptions are objects of subclasses of the class Throwable.
Java includes a set of standard exceptions that may be thrown automatically, as a result of
errors in your code, or may be thrown by methods in the standard classes in Java.
If a method throws exceptions that aren't caught, and aren't represented by subclasses of the
class Error , or by subclasses of the class RuntimeException , then you must identify the
exception classes in a throws clause in the method definition.
If you want to handle an exception in a method, you must place the code that may generate
the exception in a try block. A method may have several try blocks.
Exception handling code is placed in a catch block that immediately follows the try block
that contains the code that can throw the exception. A try block can have multiple catch
blocks that deal with different types of exception.
Search WWH ::




Custom Search