Exception Handling
Error handling in other languages
+ Error handling is done manually
+ Check return code (error code) of a function
+ Find out error description of the matching error
code
+ Troubleshoot the problem
Exception handling in Java
+ Error condition (abnormal condition) is handled by
Java Runtime System,
+ Exception means
= Error condition
= Abnormal condition
+ Exception occurs due to the occurrence of
unexpected behavior in certain statements
+ Java provides run-time error management in the
program.
Causes of Exception
+ Exceptions can arise due toa number of situations. For
example,
— Accessing aray element beyond ts size. Eg, trying t access
the 11th element ofan array when the array contains only 10
tlement.(ArrayndexOutOBoundstxceotion)
= Division by zero (Arithmetictxception)
~ Accessing a file whichis not present (FileNotFoundException)
~ Failure of /0 operations (IOException)
~ legal usage of null. (NullointerException)
= Assigning value of vale dat
(arrayStore®xception)
yet an array
What is Java Exception?
+ lava Exception isan object that describes exceptional
(error) concition that has occurred in our code.
+ General working of exception
= When an exception condition arises
+ Ths process continesutl he exepton sanded the aa system,
lt eng lowe sact net tet cesion
Exception hierarchy
| Cm
AWTError
j_ Runtimetsception
loexception
Exception
[AWTException
InstantationExceptionException classes
hrowable i the base class of ll exception classes. It is kept in
java lang package. All other exception clases are contained in
Various packages.
+ Error class describes internal system errors, which rarely occur
~ We can only naily about this ror, we ea’ take any action
+ Subclasses of LinkageError indicate that a cass has some
dependency on another class; however, the another clas has
Incompatiby changed after tre compilation of the dependent
dass
+ Subclasses of VrtualMiachineérror indicate thatthe VM is
ibroken or running out of resources.
+ AWTError Is caused by a fatal error in AWT based programs
Exception classes
eption class indicates error caused by our programs and
external circumstances, Such errors can be caught, as opposed to
Error, and can be handled
untimeException: indicates programming errors
= Accessing out-of bound array
Subclasses of RuntimeException
= avraysorebeception
IndexoutorBoundéxcepsion
Exception classes
+ The lOException class describes errors related to
input/output operations:
— Invalid input (InterruptedlOException)
— Reading past the end ofa file (EOFException)
~ Opening a nonexistent file (FileNotFoundException)
Uncaught exception
‘lass UncaughtDemol
public static void main(String ares)
int d=0;
int r=50/d;
,
+ AWTException class describes errors caused by
AWT operations.
Uncaught exception Uncaught exception
runing the rags
="
po one
ant reso/az
| ,
public static votd main (String{] azae) ¢
| ytethod Q 7
>
>Uncaught exception
+ Running the program
The default exception handler shows entire stack trace
Exception handling
Exception handling is managed using five
keywords
=try
—catch
= throw
throws
finally
Use of try-catch
+ Format
wn
statements that could generate error coneition
,
catch(Exception elf
[print exception information
1 ake necessary action, any
,
Without use of try-catch
Using try-catch
Using try-catch
+ Running the program
+ Any statement inside try block, following erroneous statement does
ot get executed
~ Le, wed net getAter myMethoe) elm outut
+ ut, statements after catch black do get executed,Multiple catch clauses
Pain exception ject rina method cause cal tot tasting)
Multiple catch clauses
+ Running the program: without argument
Rule for using multiple catch clauses
+ When we use multiple catch statements, the exception
subclasses must come before any of their super-classes
+ Aeatch statement that uses a superclass will catch
exceptions of that type plus any ofits subclasses,
+ Thus any subsequent catch clauses are never reached ~
called unreachable code,
+ InJava, unreachable code is error. Therefore, such
program would net get compiled
Superclass exception as a first catch
Superclass exception as a first catch
+ The program will not get compiled
Nested try statements
+ Atry statement can be inside the block of another try
+ Working,
= Each time a try statement is entered, the context of that
‘exception is pushed on the stack.
= Ifinner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try
Statements (outer one) catch handlers are inspected for 2
match
~ This continues until match for catch succeeds, oral of the
nested ty statements are exhausted,
= If no matching catch is found, the Java runtime system will
handle the exception.Nested try
class Nestestiy{
public stati vold main(String args
tl
int aceargs length;
System.outarintin(" arguments: ac};
Nested try
Ine array
arrlac]=100;
,
?
catch{ArrayndexOut0FBoundst ception e)
int 50/0: sjstem.out pint "Aray index out-of bounds
tl eh
ifacs=2) )
r=S0/toe-t; )
iface=2) catch(arithmeticfxeption et
System out prite("Division by zero: "¥e);
)
Nested try Nested try (with line numbers)
) oo,
)
Running the program: Nested try Ways to create Java Exception
+ Two ways:
— Exception gets created automatically , due to some
operation
* Done by Java runtime system
We can manually create exception and can throw it.
+ Programmers write code, uses throw clauseException handling mechanism
+ Claiming an exception
+ Throwing an exception
+ Catching an exception
Exception handling mechanism
Claiming an exception
= itll tothe compiler that during execution ofthis function,
something wrong can happen,
puble wed mysetnol rows aceon
~ The caller of such method has to use either try-catch or needs to
pass exception tos caller by specifying throws
Throwing an exception
~ The method that decared an exception can throw exception
object
Catching an exception
= catching af thrown exception is dane using catch statements
Checked exception and unchecked
exception
+ Unchecked exceptions
~ These exceptions are rot required tobe declared or cme sing
~ Error, RuntimeE ception, and subelasses are unchecked exceptions
= Seames: rehmeticaception, ArrayindexOutOFSoundséacertion,
+ Checked exceptions
~ Forallocter excpsions, method needs to claim/declare exception
~ Examples: ClassNotFoundExcepton,lOFxception,
Irteruptedexespion
Checked Unchecked exception: example
impor javaio.
class CheckUncheck
public stale void uncheckMethoett
System.out pritin(> Inside uncheckMethol)");
‘throw new RuntimeException("Demo; Runtime error");
,
public static vol checkMethod) throws 10Exception{
System out printin("> Inside checkMethod”);
‘throw new IOException("Demo: ]OException")
Checked Unchecked exception: example
(cont...)
publ sated matnstinl a
tw
unchecetro)
)
cateh(Runtimetxceptione}
‘Syster.out pritin(> During 2 call to uncheckMethod!)
“eh
}
Checked Unchecked exception: example
(cont...)
oe
ecko
,
catenloescepton ek
System out pritin"> During a callto checkMethod)
"eh
,
}Running Checked Unchecked exception:
example
Throwing checked exception without
declaration
+ Throwing checked exception without declaration will
‘cause compilation error.
* The following code is invalid
public static void checkMethod() {
‘System.out. printin("> Inside checkMethod{)");
throw new IOException("Demo: IOException");
Throwing checked exception without
declaration
+ Compiler will generate errors
Methods related to exception
+ Some methods of Throwable class
— public String getMessage()
+ Returns detalee descrintion ofthe Throwable abject
= public String toString()
+ Returns short description ofthe Throwable object,
— public String getLocalizedMessage()
+ Returnsa localized description of the Throwable objec.
= public void printstacktracef)
+ Itprints the Throwable object ane its trace information on
the console
Rethrowing exceptions
+ Ifthe caller of method wants to do some processing related to
the thrown exception, the called method can rethrow the
exception, even after the called method has done processing
ofits part
tr
U[ statements;
)
catch{TheExceptionClass elf
U/ perform operations before exit
throw e
)
The finally clause
+ The finally clause is useful when a method is using resources
{fle db connection, network connection) and the method
retuens prematurely.
wr
}eateh(Throwable e}
}
finally
)
+ The finally blocks executed in ll circumstances, whether
exception occurs or does not occur
+ The finally black will execute even if na matching catch
statements founThe finally clause
+ Any time a method is about to return to the caller,
from inside a try-catch block, via an uncaught
exception or explicit return statement, the finally
clause is executed just before the method returns.
+ The finally clause is not compulsory
+ But, a try statement requires at least one catch or
a finally clause.
Finally demo
clas FnallDemo{
publ static void throwExceptionMethod(
tt
sytem out rntnt> inside throwExceptionMethot")
throw new Runtimetxception Fray Demo: Runtime
enor
1
‘aly
System outprntin"> Finally of throwEsceptionMethod),
:
Finally demo (cont...)
public static void eturnfromIryMethod()
wt
System out riatin(> Inside returnFromtryMethoe");
)
finaly,
System out pritin"> Finally of
returnFromtryMethod()"
}
)
Finally demo (cont...)
public static vod svecessulMethoa
tr
System out printi("> Inside successfulMethod")
)
finaly,
System out printi("> Finally of successtulMethoa");
}
Finally demo (cont...)
publi stati vie main(String ares}
wt
throwExceptionMethodl}
)
catehlException et
‘System out rintin(’> Exception caugh
}
returnFromTryMethodl)
successfulMethodt);
Running: Finally demoException in GUI based program
+ If exception of a subclass of Exception occurs in a
GUI program?
— Java prints the error message on the console (program
isnot terminated)
— Program continues its user interface processing loop.
Test of ArrayindexOutOfBoundsException
Arrayindex: a GUI based application
impor java aut
import java.awtevent.*;
dass Arrayindex extends Frame implements ActionListener
Sting!) ste") °CE,"CL,"EC"};
TextField f2=new TextFieid(20);
TextField t=new Textfiela(¢o},
Button benew Button”
Arrayindex: a GUI based application
(cont...)
public Arrayindex(String title
super(titl);
Panel pi=new Panel); pl.add{new Label"index");
pladd(tf); pladé(new Label('Value");
pladd(t2);ada("North'o1;
Panel p2=new Panel); p2.add{b)
adel"South"p2);
b addActionListenertthis);
setSize(600,100};
setvisible(tue);
Arrayindex: a GUI based application
(cont...)
publi static wold mn Sing] 3
now Seayndet 30 axe
,
public od actonerormndActonent ae
Intndoritegersanicn( gettext)
™
Strngleesininaer; Baste
fateh ArmndexOuOfBounabeepion
‘Waseten leate Enter indexn the range Oto lt ent 1);
Running the program
Vala incex
+ sIvalid index
non ESC as cninereoes
aWithout exception handling
public void actionPerformed(Actiontvent ae}{
int index=integer parselnt(t getText().trim());
String value-list[index];
‘f2.setTent(value);
Running the program
User defined exception classes
+ In some situations, we would like to implement our own
exception types to handle application specific situations
Eg, entering negative amount in withdraw operation
~ ryt issue a book (in concurrent environment) that has just
become unavailable
+ We can do this by defining a subclass of Exception
+ Exception class has no methods ofits own, it derives from
Throwable
+ We are not required to implement any method in our own.
exception class. Thelr presence indicates that they are
exception classes {anything derived from Exception)
Account operation using user defined
exception
+ We have Account object, which allows the
following two operations
—withdraw()
—deposit()
* For withdraw() operation,
= User may pass negative value
= Sufficient balance isnot available
+ For deposit operation,
= User may pass negative value
Account
dacs Account
private in 1;
prvatedovble balance;
‘Account 1, double lance
this balancesbatnee;
ublicine get
public double getalarcei
return balance
Account
(cont...)
public void withdraw{double amount}throws
NegativeAmountException,
InsufficlenFundexcepton(
iamaunt