Module-4 Part-B Exception Handling (book notes)
Module-4 Part-B Exception Handling (book notes)
CHAPTER
10
Exception Handling
Condition that arises in a code sequence at run time. In other words, an exception is a
TEun-ime error Incomputer languages that do not supportexception handling, errors
must be checked andhandled manually-typically through the use of error codes, and so
on. This approach is as cumbersome as it is troublesome.Java's exception handling avoids
these problems and, in the process,brings run-time error management into the object
oriented world.
Exception-Handling Fundamentals
A Java exceptionis an object that describes an exceptional(that is, error) condition that has
Occurredina piece of code. When an exceptional condition arises, an object representing
that exceptionis created and throwi in the method that caused the error. Thatmethod may>
Choose jo handle the exceptionqtself)or pass on. Bither way, at some point, the exception
it
iscaught and processed. Exceptions can be generated by the Java run-time svstem, they
or
can be manually generated by your code. Exceptionsthrown by Java relate to fundamental
errors that violate the rules of theJava language the constraints of the Java execution
or
environment. Manually generated exceptions are typically used to report some error condition
to the caller of a method.
Java exception handling is managedviafive keywords) try, catch,throw, throws, and
finally. Briefly, here is how they work. Program statements that you want tojmonitor for
exceptions are contained within a tryblock. If an exception occurs within the try block, it is
thrown. Your codecan catch this exception (using catch) and handle it in some rational manner.
try {
205
hrowble syen l as)
elass 1)
(sub
Eceptm
Pxpectel to
206 Part I: The Java Language Rntielceton (aught undes
catch (ExceptionTypelexOb) |
1/exception handler for ExceptionTypel indeainy
1
catch (ExceptionType2exOb) (
1/exception handler for ExceptionType2
Yn-time systm
Here, ExceptionTypejis the type exception that has occurred. The remainder of this chapter
of
describes how to apply this framework.
Exception Types
All exceptiontypes are subclasses of the built-in class Throwable. Thus, Throwable is at the
top.ofthe exception class hierarchy. Immediately below Throwable are twosubclassesthat
partition exceptionsinto two distinct branches.One branch is headed by ExCeption. This class
is used for exceptional conditionsthat user programs should catch. This is also the class that
you will subclass to create your own custom exceptiontypes. There is an important subclass
of Exception,called RuntimeException. Exceptions of this type are automatically defined for
the programs that you write and include things such as division by zero and invalid array
indexing
The other branch is topped by Error, which defines 'exceptions that are not expected to
be caught under normal circumstancesby your program. Exceptions of type Error are used
by the Java run-timesystem to indicate errors having to do with the run-time environment,
itself.Stack overflowjis an example of such an error. This chapter will not be dealingwith
exceptions of type Error, because these are typically created in response to catastrophic failures
that cannot usually be handled by your program.
Uncaught Exceptions
Before you learn(how to handle exceptions in your program,jtis useful(to see what happens
when you don't handle them. Thissmall program includes án expressionthatintentionally
causes a divide-by-zero errof:
Class Exco
public static void main (String args (] ) {
int d = 0;
int a =42 /d;
When the Java run-time system detectšjthe attempt toldivide by zerojit gonstructs a
new exception object and then throzUs this exception. This causes the execution of ExcO to
Chapter 10: Exception Handling 207
stop, because once an exception has beerthrown)it must becaught byan exception handler
and dealt with immediately. Inthis example, we haven't supplied any exception harndlers of
our own, sothe exceptionis caught by the default handler provided bythe Java run-time
system. Any exception that is not caught by your program will ultimately be
the delault
stack
processed by
handler Thedefaulthandler displays a string describingthe exception, prints a
trace irom the point at which the
exception occurred,and terminates theprogram.
I
PART
java.lang.ArithmeticBxception: / by zero
at Exc0.main (Exc0.java:4)
Notice how the class name,Exc0; the method name,main; the filename, Exc0.java;
and the line number,4,are all included in thesimple stack trace. Also, notice that the type
of exception thrown is a subclass of Exceptionälled (ArithmeticException,which more
specificallydescribes what type of error happened. As discussed later in this chapter, Java
supplies several built-in exception types that match the various sorts of run-time errors that
can be generated.
Thestack trace will always show the sequence of method invocations that led up to
the For example, here is another version of the preceding program that introduces the
error.
(Tha Eyd");
public static void
Excl.subroutine ()
main (String args
;
[I) {
3 Systernvodivd
o|PEro:Atmehc
Excppion : dhide
The resulting stack trace from the default exception handler showshow the entire call
stack is displayed:
java.lang.ArithmeticException: / by zero
at Exc1. subroutine(Exc1.java:4)
at Excl.main (Excl.java:7)
the bottom of the stack main's which the call to subroutine( ),
As you can see, is line 7, is
which caused the exception at line 4. The call stack is quite useful for debugging, because it
the error.
pinpoints the precise sequence of steps that led to
running and printed a stack trace whenever an error occurred! Fortunately, it is quite easy
to prevent this.
To guard against arnd handle a run-time error, simply enclose the code that you want
to monitor inside a try block. Immediately following thetry block, include acatch clause
that specifies the exception type that you wish to catch. To illustrate how easily this can be
done, the following program includes a try block and acatch clause that processes the
ArithmeticException generated by the division-by-zeroerror: class A
meinmgl ag
elass Exc2 statsc vod
pblic
public static void
int d, ai
main (String args ()) ( it a15,b50;
Ctryl //monitor a block of code.
d = 0;
3
a = 42/ d;
System. out.print ln("This will not be printed. ");
} catch (Arithmet icExcept ion e) (// catch divide-by- -zero
zero errr
System.out.print ln ("Division by zero.");
Division by zero
After catch statement
Notice that the call to println() inside the try block is never executed. Once an exception
isthroun program control transfers out of the try blockinto the catch block. Put differently.
catch is not "called,"soexecution never "returns" tothe try block from a catch. Thus, the
line "This will not be printed. is not displayed. Once the catch statement has executed,
program controlcontinues with the next line in the program following the entire try/catch
mechanism.<
A try and its catch statement form a unit) The scope of the catch clause is restricted to
those statements specifhed by the immediately preceding try statement. A catch statement
cannot catch an exception thrown by another try statement (except in thecase of nested try
statements, described shortly). The statements that are protected bytrymustbe surrounded
bycurly braces.(That is, they must be within a block.,You cannot use try on asinglestatement.
The goal ofnost well-constructed catch clauses should be to resolve the exceptional
condition and then continue on as if the error had never happened. For example, in the next
are
program each iteration of the for loop obtains two random integers. Those two integers
divided by each other, and the result is used to divide the value 12345. The final result is put
into a. If either division operation caues a divide-by-zero error, it is caught, the value of a is
set to zero, and the programcontinues.
// Handle an exception and move on.
import java,utíl, Random ;
class HandleError (
public static void main (String args(]) {
Chapter 10: Exception Handling 209
b= r.nextInt ();
PARTI
c = r.nextnt();
a = 12345 / (b/c);
} catch (Arithmet iCException e){
System. out.print ln("Division by zero.");
a = 0; // set a to zero and continue
System.out.println("a: n+ a) ;
statement by simply passing the exception as an argument. For example, the catch block
in the preceding program can be rewritten likethis:
catch (ArithmeticException e) {
System.out.println ("Exception: " + e);
a = 0; // set a to zero and continue
When this version is substituted in the program, and the program is run, each divide-by
int a = args.length;
System. out.println (a = "+ a);
int b= 42/ a;
int c[] = 1 }:
c [42) 99;
} catch (Arithmet icExcept ion e)
System. out.println ("Divide by 0: "+ e);
)catch (Array IndexOutofBoundsException e) {
C:\>java MultiCatch
a =0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
try {
int a = 0;
int b 42 / aj
) catch (Exception e) {
Chapter 10: Exception Handling 211
{
System. out. println ("This is never reached. "); PARTI
If youtry to compile this program, you will receive an error message stating that the
second catch statement is unreachable because the exception has already been caught. Since
ArithmeticException is a subclass of Exception, the first catch statement will handl€ alI
Exception-based errors,including ArithmeticExeption. Thís means that the second catch
statement will never execute. To fixthe problem, reverse theorder of thecatch statements.
Each time a try statement is entered,the context of that exception is pushed onthe stack. Ifan
inner try statement does not have a catch handler for a particular exception,the stack is
unwoundand the next trystatement'scatch handlers are inspectedfor a match.Thiscontinues
until one of the catch statements succeeds,or until all of the nestedtry statements are exhausted.
If no statement matches,then theavarun-time systemwill handle the exception.Here
catch
As you can sce, this program nests one try block within another. The program worksas
follows. When you execute the program with no command-line arguments, a divide-by-zero
command-line
exception is generated b the outer try block. Execution of the program with one
exception from within the nested try block. Since the
argumentgenerates a divide-by-zero
try block, where it is
inner block does not catch this exception, it is passed on to the outer
handled. If you execute the program with two command-line arguments, an array boundary
within the inner block. Here are sample runs that ill ustrate
exception is generated from try
each case:
C:\>java NestTry
Divide by 0: java.lang.ArithmetiCException: / by zero
nested via
/* Try statements can be implicitly
calls to methods. */
{
class MethNestTry
static void nesttry (int a){
try nested try block
// used,
/* If one ommand-line arg i8
then a divide-by-zero exception
following code. */
will be generated by the
= a/ (a-a); // division by zero
if (a==l) a
Chapter 10: Exception H andling 213
try (
int a = args.length;
throw
exceptionsthat are thrown by the Javarun-time
system.
So far, vou have only been catching
using the throw
However, it is possible for your program to throw an exception(explicitly,
statement. The general form of throw is shown here:
throw Throwablelnstance;
or a subclass of Throwable.
HereThrowablelnstance mustbe an object of type Throwable
as well as non-Throwable classes, such as String and
Primitive types, such as int or char,
are(wo waysyou can obtain aThrowableobject:
Object, cannot be used as exceptions. There
clause, or creating one with the new operator.
using a parameter in a catch
statement; any subsequent
The flow ofexecution stops immediately after the throw
block isenspected to see if it has a
statements are not executed. The
nearest enclosing try
A alnew
public static void main(String args (J)
at shsw ()
3 Soy
try (
demoproc ();
e){ End');
} catch (NullPointerException
System. out .println ("Recaught:
+ e) ;
eqesseje).
) shing
is diply hn obyect
)
print( or printin(0.Itcan
Throwable.
type Error or RuntimeException, or any of their subclasses. Allother exceptions that a method
can throw must be declared in the throws clause.If they are not, a compile-time error will result.
1/body of method
Here, rception-list s a comma-separated list of the exception that a method can throw.
Following is an exampleof anincorrect program]that trie to throw anexception that it
doesnot catch.Because the program does not specify a throws clause to declare this fact, the
program will not compie.
("
System.out.print ln Inside throwOne. "):
throw new IllegalAccess Exception (" demo") ;
throwone () :
To make this example compile, you need to.maketwochanges First you need to declare
that throwOne( ) throws IllegalAccessExceptionl Second) main( )must define a try/catch
statemerntthat catches this exception.
The corrected example is shown here:
try (
throwone ();
} catch (IllegalAccess Exception e) {
System.out .println ("Caught " + e);
inside throwOne
caught java.lang. IllegalAccessException: demo
216 Part I: The Java Language
finally
When exceptions are thrown, execution in a method takes a rather abrupt,nonlinear path
that alters the normal flow through the mnethod, Depending uponhow the method is coded,
it is even possible for an exception to cause the method prematurely.This could
to return
be a problem in some methods. For example, if a method opens a file upon entry and
closes it upon exit, then you willnot want the code that closes the file to be bypassed
by the exception-handling mechanism. The finally keyword is designed to address this
contingency.
finally creates a block of code that will be executed after atry/catch]block has
completed and beiore the code following the trylcatch block. The finally block will
execute whether or not an exception is thrown. If anexception is thrown, the finally
block will execute even if no catch statennent matches the exception.Any time a method
isabout to returnto the caller from inside a trylcatch block,via an uncaught exception or
an explicit return statement, the finally clause is also executed just before the method
returns. This can be useful for closing file handles and freeing up any other resourcesthat
might have been allocated at the beginning of a method with theintent of disposing of them
before retuming. The finally clause is optional. However, each try statement requires at
least one catch or a finally clause.
Here is an example program that showsthree methods that exit in various ways, none
without executing their finally clauses:
1/Demonstrate finally.
class FinallyDemo (
1/ Through an exception out of the method.
static void procA () {
try {
Systen. out.println ("inside proCA") ;
throw new Runt imeException (" demo");
)finally {
System. out.println s finally");
("procA'
try {
try {
System, out.println ("inside procc");
} finally {
Chapter 10: Exception W andling 217
procB (0;
procc (0 :
REMEMBER Ifa finally block is associated with a try, the finally block will be executed upon
conclusion of the try.
inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procc's finally
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable
interface.
is quite casy
Throwable).
to do:just
Your subclasses
deine a
don't
subelass of (whichis, of course,a subclass of
Exception
need toactuallyimplementanything -it is their existenc
I
PART
Method Descrlptlon
Throwable getCause( )
Returns the exception that underlies the current
exception. If there is no underlying exception, null
is returned.
You may also wish to override one ormore of these methods in exception classes that you
Create.
Exception definesfour constructors]Two were added by JDK 1.4 to support çhained
exceptions, described in the next section. The other two are shown here:
Exception( )
Exception(String msg)
The first form creates an exception that has no description. The second form lets you specify
MyException (int a) {
detail = a;
class ExceptionDemo
static void compute (int a) throws MyException
{
try {
Compute (1) ;
compute (20);
) catch (MyException e)
{
+ e);
System. out .println ("Caught "
is quite
calledMyException. This subclass
This example defines a subclass of Exception
method that displays the
simple: has only a constructor plus an overloaded toString()
it
Chapter 10: Exeeption Wandling 221
Chained Exceptions
Beginning with JDK 1.4, a new feature has been incorporated into
the exception subsystem:
chained erceptions. The chained exception feature allows you to
associate another exception
with an exception.This second exception describes the cause of the first
exception.For example,
imaginea 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 occured,
which caused the divisorto 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, andany other situation in which layers of
exceptions exist.
Toallow chained exceptions, two constructors and two methods were added to Throwable.
Theconstructors 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 specifya 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 in Table 10-3 and are repeated here for the sake of
discussion.
Throwable getCause( )
Throwable initCause(Throwable causeExc)
The getCause() method returns the exception that underlies the currentexception.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. However, the cause exception
can be set only once. Thus, you can call initCause( ) only once for each exception object.
Furthermore, if the cause exception was set by aconstructor, then you can't set it again
using initCause( ). In general, initCause( ) is used to set a cause forlegacy exception classes
that don't support the two additional constructorsdescribed earlier.
Here is an example that illustrates the mechanics of handling chained exceptions:
1| create an exception
Null PointerException e =
new Null PointerException ("top layer");
1/ add a cause
e.initcause (new ArithmeticException ("cause") );
throw e;