0% found this document useful (0 votes)
5 views

Module-4 Part-B Exception Handling (book notes)

Uploaded by

SAMANVITA Rd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Module-4 Part-B Exception Handling (book notes)

Uploaded by

SAMANVITA Rd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

MODULE 8-4(PAR- B)

CHAPTER
10
Exception Handling

his chapterexamines Java's exception-handling mechanism. Anlexception is anyabnormal

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.

System-generated exceptions are automaticallythrown by theava run-time system To


Lmanually throw an exception,use the keyword throw. Any exception that is thrown out of
ameihodmust be specifiedassuch by athrows clause. Any codethat absolutely must be
executed after altryblock completesis put in a finally block.

Thisis the generalform of an exception-handlingblock:

try {

1/block of code to monitor for errors

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

1/ .. e9: Stock overfb


finally (
/block of code to be executed after try block ends

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

Here is the exception generated when this example is executed:

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.

same error but in a method separate from main(): class A


ugs
vjd meim (Stimgl?
slie sa;e
class Excl {
Static void subroutine
int d = 0;
() { ja13,bo,c,
int = 10/d;
a

(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

Using try and catch


Although the exception handler provided by thelJava run-time systemis useful for
default

debuggingyou will usually want to handle an exception yourself. Doing soprovides(two


benefits. irst,it allows you to fix the error.Second,lit prevents the program from automatically
termínating,Most users would be confused (to say the least) if your program stopped
208 Part I: The Java Language

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.");

System.out .println("Aftercatch statement.");

This program generates the following output:

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

int a=0, b=0, C=0;


Random r = new Random ();

for (int i=0; i<32000; i++){


try {

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) ;

Displaying a Description of an Exception


Throwable overrides the toString( )method (defined by Object) sothat it returns a string
containing a description of the exception. You can display this descriptionin a println

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

zero error displays the following message:

Exception: java.lang.ArithmeticException: ./ by zero

While it is of no particular value in this context,the ability to display a descriptionof


an exception is valuable in other circumstances-particularly when you are experimenting
with exceptions or when you are debugging

Multiple catch Clauses


In some cases, more than one exception could be raised by a single piece of code. To handle
this type of situation, you can specifytwo or more catch clauses, each catching a different
statement isinspected in order,
type of exception. When an exceptionis thrown, each catch
matches that the exXception is executed. After One catch
and the first one whose type of
after the try/catch
statement executes,the others are bypassed, and execution continues
block. The following example traps two different exception types:

// Demonstrate multiple catch statements.


class Multi Catch (
public static void main (String args ()){
try {
210 Part I: The Java Language

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) {

System.out .println("Array index oob: "+ e);


System, out.print ln("After try/catch blocks .") ;

programwill cause a division-by-zero exception if it is started with no command


This
linearguments,since a will equal zero. It will survive the division if you provide a
command-lineargument,setting a to something larger than zero. But it willcause an
ArraylndexOutOfBoundsException, since the int array c has a length of 1, yet the program
attempts to assign a value to c[42].

Here is the output generated by running it both ways:

C:\>java MultiCatch
a =0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

C:\>java MultiCatch TestArg


a = 1

Array index oob: java.lang.ArrayIndexOutofBoundsException:42


After try/catch blocks.

When you use multiplecatch statements, it is important to remember that exception


subclasses must Come before any of their superclasses.This is because a catch statement
that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a
subclass would never be reached if it came after its superclass.Further,in Java, unreachable
code isan error. For example, consider the following program:

/* This program contains an error.

A subclass must come before its superclass in


a series of catch statements. If not,
unreachable code will be created and a
compile-time error will result
*/
class SuperSubCat ch (
public static void ma in (String args ]) {

try {
int a = 0;
int b 42 / aj
) catch (Exception e) {
Chapter 10: Exception Handling 211

System. out.println ("Generic EXception catch. ");

/* This catch is never reached because


ArithmeticExGeptionis
catch (ArithmeticException
a
subclass of Exception. */
e) // ERROR - unreachable

{
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.

Nested try Statements


The try statement can be nested. That is, a try statement can beinsidethe block of another try.

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

isan example that uses nested try statements:

// An example of nested try statements.


class NestTry
public staticvoid main (String args[]) {
try {
,
int a = args.length;

/* If no command-line args are present,


the following statement will generate
a divide-by-zero exception. */
dodi int b = 42 / a;

System. out.println ("a = n+ a);


try /
nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
ime if (a==1) a = a/ (a-a) ; J| division by zero

nested /* If two command- 1ihe args are used,


then generate an out-of -bounds exception, */
if (a==2) {
int c[) = {1 }i
212 Part I: The Java Language

c [42] = 99; // generate an out-of-bounds exception

} catch (ArrayIndexOutofBoundsExcept ion e) (


System.out .println("Array index out-of -bounds: "+ e)i

)catch (ArithmeticExcept ion e) {


System. .println out ("Divide by 0: " + e);

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

C:\>java NestTry One


a = 1
/ by zero
Divide by 0: java.lang.ArithmeticException:

C:\>java NestTry One Two


a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42
obvious ways when method calls are involved.
Nesting of try statements can occur in less
For example, you can enclose a call to a
method within a try block. Inside that method is
within the method is still nested inside the outer try
another try statement. In this case, the try
Here previous program recoded so that the nested
block, which calls the method. is the

try block is moved inside the method


nesttry(0:

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

/* If two command -linearge are used,


then generate an out-of -bounds exception. */
if (a==2) {
int cU ): (1
c[42]- 99; /1 generate an out-of-bounds exception PART

) catch (ArrayIndexOutofBounds Exception e) {


(
System,out.print ln "Array index out-of -bounds: " + e);

public static void main (String args [)) (

try (
int a = args.length;

/* If no command-line args are present,


the following statement will generate
a divide-by-zero exception. */
int b.= 42 / a;
System. out.println ("a = + a); "
nesttry (a)
e)(
;
catch (ArithmeticExcept ion
"+
}
System. out.println ("Divide by 0:
e);

program to that of the preceding example.


The output of this is identical

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

of exception, If it does find a match,control is


catch statement that matches the type
try statement is inspected,and
to that statemernt. If not, then the next enclosing
transferred
exception handlerhalts the program
so on. fno matching catch is found]then the
default

and prints the stack trace.

-Tt is use madhol boly to thrvw ecem.


ny
-thyw
keywovd aJys
214 Part I: The Java Language

a sample program that creates arnd throws an exception)The handler


that catches
Here is

the exceptionrethrows it to the outer handler.


class fomden
1/ Demonstrate
class ThrowDemo
throw. enden vajd shgwe)
static void demoproc () {
try
throw new NullPointerException ("demo")
} catch (Null PointerException e)

System. out.println ("Caught inside demoproc. ");


throw e; // rethrow the exception maun angsi

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

Fitst, main() sets up an exception


to deal with the sameerror.
This program gets two chances
The demoproc() method then sets up anotherexception
context and then calls demoproc(). which
throws a new instance of NulIPointerException,
handling context and immediately output:
line. The exception is then rethrown.
Here is the resulting
is caught on the next

Caught inside demoproc.


PointerException:demo
Recaught: java.lang. Null
Pay
how tocreate one of Java's standard exception objects.
The program also illustrates

close attention to this line:

Null PointerException ("demo");


throw new
of Java's built
of NullPointerException. Many
to construct an instance
new is parameterand one that
Here, used
withmo
least two constructors.
pne
in run-time exceptionshaveat argument specifies a string that
the second formis used,the
takes a string parameterWhen
describes the exception. This string is displayedwhen
), which
s
theobject used as anargument
jo
is defined by
to getMessage(
also be obtained by
a call

)
print( or printin(0.Itcan
Throwable.

Shrows it must specify this


an exception that it does not handle,
(Ifa method is capable of causing exception. You do
method can guard themselves against that
behavior so that callers of the throws clause lists the types
clause in the method's declaration)A
thisby including a throws for all exceptions,
except those of
This is necessary
of that a method might throw.
exceptions
Chapter10: Exception Handling 215

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.

This is the general form of a method declaration thatincludes a throwsclause:

type method-name(parameter-list)throws exception-list 1


PART

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.

1/ This program contais an error and will not compile.


class ThrowsDemo
static void throwOne () {

("
System.out.print ln Inside throwOne. "):
throw new IllegalAccess Exception (" demo") ;

public static void main (String args (] ) {

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:

// This is now correct.


class ThrowSDemo {
static void throwOne () throws Il1legalAccessException {

System. out.println ("Inside throwOne. ");


throw new IllegalAccessException (" demo ");

public static void main (String args[]) {

try (
throwone ();
} catch (IllegalAccess Exception e) {
System.out .println ("Caught " + e);

Here is the output generated by running this example program:

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'

//Return from within a try block.


static void procB () {

try {

System. out.println ("inside procB");


return;
} finally {

System. out .println ("procB' s finally") ;


)

// Execute a try block normally.


static void procc() {

try {
System, out.println ("inside procc");
} finally {
Chapter 10: Exception W andling 217

System.out.print ln ("procc's finally") ;

public static void main (String


args []){
try (
procA();
catch (Exception e)
I
PART

System. out.println ("Exception caught ");

procB (0;
procc (0 :

Inthis example, procA() prematurely breaks out of the try by throwing an


exception.
The finally clause is executed on the way out. procB0's try statement is exited via a return
statement.The finally clause isexecuted before procB)returns. In procC), the try statement
executes normally, without error. However, the finally block is still executed.

REMEMBER Ifa finally block is associated with a try, the finally block will be executed upon
conclusion of the try.

Here is the output generated by the preceding program:

inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procc's finally

Java's Built-in Exceptions


Inside the standard package java.lang, Java defines several exception classes. A few have
been used by the preceding examples. Themost general of these exceptions are subclasses

of the standard type RuntimeException. As previously explained,these exceptions need


not be inclhuded ín any method's throws list.In the language ofJava, these are called
or
unchecked exceptions because the compilerdoes not check to see if a method handles
The unchecked exceptions defined in java.lang are listed in
throws these exceptions.
Table 10-1. Table 10-2 lists those exceptions defined by java.lang that must beincluded
in a method's throws list if that method can generate one of these exceptions and does
not handle it itself. These are called hecked exception Javadefines several other types
to its various class libraries.
of exceptions that relate
218 Part I: The Java Language

Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.

ArraylndexOutOfBoundsException |Arrayindex is out-of-bounds.

ArrayStoreException |Assignment ta an array element of an incompatible type.

ClassCastException Invalid cast.

EnumConstantNotPresentException An attempt is made to use an undefined enumeration value.


llegalArgumentException |llegal argument used to invoke a method.

llegalMonitorStateException |llegal monitor operation, such as waiting on an unlocked


thread.

llegalState Exception Environment or application is in incorrect state.

|llegalThreadStateException Requested operation not compatible with current thread


state.

IndexOutOfBoundsException Some type of index is out-of-bounds.

NegativeArraySize Exception Array created with a negative size.

NullPointerException |Invalid use of a null reference.

NumberFormatException |Invalid conversion of a string to a numeric format.

SecurityException |Attempt to violate security.

StringindexOutOfBounds |Attempt to index outside the bounds of a string.

TypeNotPresentException Type not found.

UnsupportedOperationException An unsupported operation was encountered.

TABLE 10-1 Java's Unchecked RuntimeExceptionSubclasses Defined in java.lang

Exception Meaning
ClassNotFoundException Class not found.

CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable
interface.

IllegalAccessException |Accessto a class is denied.


InstantiationException Attempt to create an object of an abstract class or interface.

InterruptedException |Onethread has been interrupted by another thread.

NoSuchFieldException |A requested field does not exist.


NoSuchMethod Exception A requested method does not exist.

TABLE 10-2 Java's Checked Exceptions Defined in java.lang


Chapter 10: Exception Handling 219

Creating Your Own Exception Subclasses


Although lava's built-in exceptions handle most common errors, you will probably want
to create your own exception types to handle situations specific to your applications. This

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

in the type systemn that allows you to Use them as exceptions.


The Exception class does not define any methods of itsown,
It does,of course, inherit
those methods proviced by
uowable. Thus, all exceptions, including those that you create,
have the methods defined by Throwable availableto them. They are shown in Table 10-3.

Method Descrlptlon

Throwable filllnStackTrace( Returns a Throwable object that contains a completed


)
stack trace. This object can be rethrown.

Throwable getCause( )
Returns the exception that underlies the current
exception. If there is no underlying exception, null
is returned.

String getLocalizedMessage( ) Returns a localized description of the exception.

String getMessage( ) Returns a description of the exception.

|Returns an array that contains the stack trace, one


StackTraceElement[ lgetStackTrace(
)
element at a time, as an array of StackTraceElement.
The method at the top of the stack is the last method
called before the exception was thrown. This method

isfound in the first element of the array. The


StackTraceElement class gives your program access
toinformation about each element in the trace, such
as its method name.
Throwable initCause(Throwable |AssociatescauseExc with the invoking exception as a
causeExc) cause of the invoking exception.Returns a reference
to the exception.

void príntStackTrace( ) Displays the stack trace.

|Sends the stack trace to the specified stream.


void printStackTrace(PrintStream
stream)
Sends the stack trace to the specified stream.
void printStackTrace(PrintWriter
stream)
Sets the stack trace to the elements passed in
void setStackTrace(StackTraceElement
elementsl ])elements. This method is for specialized applications,

not normal use.

Returns a String object containing a description of the


|String toString( )
exception. This method is called by printin( ) when
outputting a Throwable object.

TABLE 10-3 The Methods Defined by Throwable


220 Part I: The Java Language

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

a description of the exception.


Although specifying a description when an exception is created is often useful, somnetimes
it is better to override toString( ). Here's why:The version of toString) defined by Throwable
(and inherited by Exception) first displays the name of the exceptionfollowed by a colon, which
is then followed by your description. ByoverridingtoStringl ), you can prevent the exception
This makes for a cleaner output, which is desirable in
name andcolon from being displayed.
Some cases.
declares a new subclass of Exception and then uses that subclass
The following example
an error conditionin a method. It overrides the toString) method, allowing a
to signal

carefully tailored description of the exception to be displayed.

// This program creates custom exception a type.


class MyException extends Exception
{
private int detail;

MyException (int a) {

detail = a;

public String tostring (){


return "MyException [" + detail + "]";

class ExceptionDemo
static void compute (int a) throws MyException
{

System. out.println ("Called compute ("


+ a + ")");
if (a > 10)
throw new MyException (a);
System. out.println ("Normal exit");

public static void main (Stringargs []) {

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

value ofthe exception. The ExceptionDemoclass defines a method


named compute( ) that
throws MyException object. The exceptionis thrown when
a
compute()'s integer parameter
is greater than 10. The main() method sets up an
exception handler for MyException, then
alls compute() with a legal value (less than 10)and an illegal one to
show both paths through
the code. Here is the result:
PARTI

Called compute (1)


Normal exit
Called compute (20)
Caught MyException (20]

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/ Demonstrate exception chaining.


class ChainExcDemo
statíc void demoproc () {
222 Part I: The Java Language

1| create an exception
Null PointerException e =
new Null PointerException ("top layer");

1/ add a cause
e.initcause (new ArithmeticException ("cause") );
throw e;

public static void main (String args [) ) {


try {
demoproc () :
)catch (NullPointerException e) {
1| display top level exception
System. out.println ("Caught: " + e);

1/ display cause exception


4
System.out .println ("Original cause:
e.getCause ());

The output from the program is shown here:

Caught: java.lang.Null PointerException: top layer


Original cause: java. lang.ArithmetiCException: cause

In this example, the top-level exception is NulIPointerException. To it is added a cause


exception,ArithmeticException. Whèn the exception is thrown out of demoproc(),it is
caught by main(). There, the top-level exception is displayed, followed by the underlying
exception, which is obtained by calling getCause( ).
Chained exceptionscan be carried on to whatever depth is necessary. Thus, the cause
exception can, itself, have a cause. Be aware that overly long chains of exceptions may
indicate poor design.
Chained exceptionsare not something that every program will need. However, in cases
in which knowledgeof an underlying cause is useful, they offer an elegant solution.

You might also like