1. Page 1 of 13
Class Notes on Exception handling (Week - 8)
Contents:- Exceptionhandlingbasics,differenttypesof exceptionclasses,use of try& catch withthrow,throws&
finally,creationof userdefinedexceptionclasses.
ExceptionHandling in Java
The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In this Note, we will know about exception, its type and the difference between checked and unchecked exceptions.
Exception
Dictionary Meaning:Exceptionisanabnormal condition.
In java,exceptionisaneventthatdisruptsthe normal flow of the program.Itis an objectwhichisthrownat
runtime.
An exception is a problem that arises during the execution of a program. An exception can occur for many different
reasons, including the following:
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications, or the JVMhas run out of memory.
Some of these exceptionsare caused by user error, others by programmer error, and others by physical resources that
have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories of exceptions:
Checkedexceptions:A checkedexceptionisanexception that is typically a user error or a problem that cannot
be foreseenbythe programmer.Forexample,if afile istobe opened,butthe file cannot be found,anexception
occurs. These exceptions cannot simply be ignored at the time of compilation. The classes that extend
Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException,
SQLException etc. Checked exceptions are checked at compile-time.
Runtime exceptions:A runtime exceptionisanexceptionthatoccursthat probablycouldhave been avoided by
the programmer.Asopposedtocheckedexceptions,runtime exceptionsare ignoredatthe time of compliation.
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException,ArrayIndexOutOfBoundsExceptionetc.Uncheckedexceptionsare notcheckedatcompile-
time rather they are checked at runtime.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For
example,if astackoverflowoccurs,anerror will arise.Theyare also ignored at the time of compilation. Error is
irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Exception Handling
Exception Handling is a mechanism to handle runtime errors.
2. Page 2 of 13
Advantage of Exception Handling
The core advantage of exceptionhandlingisthatnormal flow of the applicationismaintained.Exceptionnormally
disruptsthe normal flowof the applicationthatiswhywe use exceptionhandling.Let'stake a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
Suppose there is 9 statementsinyourprogramand there occursan exceptionatstatement5,restof the code will not
be excecutedi.e.statement6to 9 will notrun. If we performexceptionhandling,restof the exceptionwill be executed.
That is whywe use exceptionhandling.
CommonscenariosofExceptionHandlingwhereexceptionsmayoccur
There are givensome scenarioswhere uncheckedexceptionscanoccur.Theyare as follows:
1) Scenario whereArithmeticExceptionoccurs
If we divide anynumberbyzero,there occursan ArithmeticException.
1. inta=50/0; // ArithmeticException
2) Scenario whereNullPointerExceptionoccurs
If we have null value inanyvariable,performinganyoperationbythe variable occursanNullPointerException.
1. Strings=null;
2. System.out.println(s.length()); // NullPointerException
3) Scenario whereNumberFormatExceptionoccurs
The wrong formattingof anyvalue,mayoccur NumberFormatException.Suppose Ihave astringvariable thathave
characters,convertingthisvariable intodigitwill occurNumberFormatException.
1. Strings="abc";
2. inti=Integer.parseInt(s); // NumberFormatException
4) Scenario whereArrayIndexOutOfBoundsExceptionoccurs
If you are insertinganyvalue inthe wrongindex,itwouldresultArrayIndexOutOfBoundsExceptionasshownbelow:
1. inta[]=new int[5];
2. a[10]=50; // ArrayIndexOutOfBoundsException
3. Page 3 of 13
Use of try-catch block in Exception handling:
Five keywordsusedinExceptionhandling:
1. try
2. catch
3. finally
4. throw
5. throws
try block
Enclose the code that mightthrowan exceptionintryblock.Itmust be usedwithinthe methodandmustbe followedby
eithercatchor finallyblock.
Syntaxoftry with catch block
1. try{
2. ...
3. }catch(Exception_class_Namereference_variable_or_object){ … }
Syntaxoftry with finally block
1. try{
2. ...
3. }finally{}
catch block
Catch blockisusedto handle the Exception.Itmustbe usedafterthe try block.
Problemwithoutexceptionhandling
1. class Simple{
2. public static void main(String args[]){
3. int data=50/0;
4.
5. System.out.println("rest of the code...");
6. }
7. }
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
As displayedinthe above example,restof the code isnotexecutedi.e.restof the code...statementisnotprinted.Let's
see whathappensbehindthe scene:
4. Page 4 of 13
What happensbehindthe codeint a=50/0;
The JVMfirstlycheckswhetherthe exceptionishandledornot.If exceptionisnothandled,JVMprovidesadefault
exceptionhandlerthatperformsthe followingtasks:
Printsoutexceptiondescription.
Printsthe stack trace (Hierarchyof methodswhere the exceptionoccurred).
Causesthe program to terminate.
But if exceptionishandledbythe applicationprogrammer,normal flow of the applicationismaintainedi.e.restof the
code is executed.
Solution by exception handling
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=50/0;
5.
6. }catch(ArithmeticException e){System.out.println(e);}
7.
8. System.out.println("rest of the code...");
9. } // main ends
10. } // class ends
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now,as displayedinthe above example,restof the code isexecutedi.e.restof the code...statementisprinted.
Multiple catch block
If you have to performdifferenttasksatthe occrence of differentExceptions,use multple catchblock.
5. Page 5 of 13
Rule 1: At a time only one Exception is occured and at a time only one catch block is executed.
Rule 2: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come
before catch for Exception
class Excep4{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output: (Compile time Error)
Excep4.java:8: exception java.lang.ArithmeticException has already been caught
catch(ArithmeticException e){System.out.println("task1 is completed");}
^
Excep4.java:9: exception java.lang.ArrayIndexOutOfBoundsException has already
been caught
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");
}
^
2 errors
Explanation
If you try to compile thisprogram,youwill receive anerrormessage statingthatthe second andthird catch statementis
unreachable(lookatthe error messages) becausethe exceptionhasalreadybeen caught. Since ArithmeticExceptionis a
subclassof Exception,the first catch statement will handle all Exception-based errors, including ArithmeticException.
Thismeansthat the second and third catch statement will never execute. To fix the problem, reverse the order of the
catch statements or just put the catch(Exception e) statement at last.
Modified Program
class Excep4{
public static void main(String args[]){
try{
int a[]=new int[5];
//a[10]=90; if we uncomment this line then ArrayIndexOutOfBoundsException
a[5]=30/0; // generates ArithmeticException
}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(Exception e){System.out.println("common task completed");}
System.out.println("rest of the code...");
}
}
Output:task1 is completed
rest of the code...
6. Page 6 of 13
Nested try block:
try blockwithinatry blockis knownasnestedtryblock.
Why usenested try block?
Sometimesasituationmayarise where apartof a blockmay cause one error and the entire blockitselfmaycause
anothererror.In such cases,exceptionhandlershave tobe nested
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
Example of nested try block
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
// int x=7/0; uncomment,then catch(Exception e) handled
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement”);
}catch(Exception e){System.out.println("All Exceptions handeled");}
System.out.println("normal flow..");
}
}
OUTPUT:
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
7. Page 7 of 13
other statement
normal flow..
finally block
The finallyblockisa blockthatis alwaysexecuted.Itismainlyusedtoperformsome importanttaskssuchas closing
connection,streametc.
Note:Before terminating the program, JVM executes finally block(if any).
Note:finally must be followed by try or catch block.
Why usefinallyblock?
finallyblockcanbe usedto put"cleanup"code suchas closinga file,closingconnectionetc.
case1
Programin case exception doesnot occur
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:5
finally block is always executed
rest of the code...
8. Page 8 of 13
case2
Programin case exception occured but nothandled
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
case3
Programin case exception occured andhandled
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Rule: Foreach try blockthere canbe zero ormore catch blocks,but only one finally block.
Note: The finally blockwill not be executed ifprogramexits(eitherby callingSystem.exit()or by
causinga fatalerrorthat causes theprocess to abort).
throwkeyword
So far,you have onlybeencatchingexceptionsthatare thrownbythe Java run-time system.However,itispossiblefor
your programto throwan exceptionexplicitly,usingthe throw statement.The generalformof throw isshownhere:
throw ThrowableInstance;
9. Page 9 of 13
Here,ThrowableInstance mustbe anobjectof type Throwable ora subclassof Throwable.Simpletypes, suchasintor
char, as well asnon-Throwableclasses,suchas Stringand Object,cannotbe usedas exceptions.Thereare twowaysyou
can obtain
A Throwableobject:usingaparameterintoa catch clause,or creatingone withthe new operator.
The throw keywordisusedto explicitly throw an exception. We can throw either checked or uncheked exception. The
throw keyword is mainly used to throw custom exception. We will see custom exceptions later.
Exampleofthrowkeyword
In thisexample,we have createdthe validatemethodthattakesintegervalue asaparameter.If the age islessthan18,
we are throwingthe ArithmeticExceptionotherwiseprintamessage welcometovote.
1. class Excep13{
2. static void validate(int age){
3. if(age<18)
4. throw new ArithmeticException("not valid");
5. else
6. System.out.println("welcome to vote");
7. }
8.
9. public static void main(String args[]){
10. validate(13);
11. System.out.println("rest of the code...");
12. }
13. }
Output:Exception in thread main java.lang.ArithmeticException:not valid
Exceptionpropagation:
An exceptionisfirstthrownfromthe topof the stack and if itis notcaught, itdrops downthe call stack to the previous
method,If notcaughtthere,the exceptionagaindropsdowntothe previousmethod,andsoonuntil theyare caught or
until theyreachthe verybottomof the call stack.Thisiscalledexceptionpropagation.
Rule: By default Unchecked Exceptions areforwarded incallingchain(propagated).
Programof Exception Propagation
1. class Simple{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. } // Class Simple ends
8.
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Simple obj=new Simple();
10. Page 10 of 13
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Output:exception handled
normal flow...
In the above example exceptionoccursinm() methodwhere itisnothandled,soitispropagatedtopreviousn() method
where itisnot handled,againitispropagatedtop() methodwhere exceptionishandled.
Exceptioncanbe handledinanymethodincall stack eitherinmain() method,p()method,n() methodorm() method.
The flowof executionstopsimmediatelyafterthe throw statement;anysubsequent statementsare notexecuted.The
nearestenclosing tryblockisinspectedtosee if ithas a catch statementthatmatchesthe type of the exception.If it
doesfinda match,control is transferredtothat statement.If not,thenthe nextenclosing trystatementisinspected,
and so on.If nomatching catch isfound,thenthe defaultexceptionhandlerhaltsthe programandprintsthe stack
trace.
Here is a sample programthat createsandthrowsan exception.The handlerthatcatchesthe exceptionrethrowsit to
the outerhandler.
// Demonstrate throw.
classThrowDemo{
staticvoiddemoproc() {
try {
thrownewNullPointerException("demo");
} catch(NullPointerExceptione) {
System.out.println("Caughtinside demoproc.");
throwe; //rethrowthe exception
}
}
publicstaticvoidmain(Stringargs[]) {
try {
demoproc();
} catch(NullPointerExceptione) {
System.out.println("Recaught:"+ e);
}
}
}
Thisprogram getstwo chancesto deal withthe same error.First,main( )setsupanexceptioncontextandthencalls
demoproc( ).The demoproc( )methodthensetsupanotherexception-handlingcontextandimmediatelythrowsanew
instance of NullPointerException,whichiscaughtonthe nextline.The exceptionisthen rethrown.Here isthe resulting
output:
11. Page 11 of 13
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
The program alsoillustrateshowtocreate one of Java’sstandard exceptionobjects.
Pay close attentiontothisline:
thrownewNullPointerException("demo");
Here,new isusedtoconstructan instance of NullPointerException.All of Java’sbuilt-inrun-time exceptionshave atleast
twoconstructors: one withnoparameterandone thattakesa stringparameter.Whenthe secondformisused,the
argumentspecifiesastringthat describesthe exception.Thisstringisdisplayedwhenthe objectisusedasanargument
toprint( ) or println( ).Itcan also be obtainedbya call to getMessage( ),whichisdefinedbyThrowable.
throws keyword:
If a methodiscapable of causingan exceptionthatitdoesnot handle,itmustspecifythisbehaviorsothatcallersof the
methodcan guardthemselvesagainstthatexception.Youdothisbyincludinga throwsclause inthe method’s
declaration.A throws clause liststhe typesof exceptionsthata methodmightthrow. Thisisnecessaryforall exceptions,
exceptthose of type Error or RuntimeException,oranyof theirsubclasses.All otherexceptionsthatamethodcanthrow
mustbe declaredinthethrowsclause.If theyare not,a compile-time errorwill result.
Thisis the general formof a methoddeclarationthatincludesa throwsclause:
type method-name(parameter-list)throwsexception-list
{
// body of method
}
Here, exception-listisacomma-separatedlistof the exceptionsthatamethodcan throw.
The throws keyword isusedtodeclare anexception.Itgivesaninformationtothe programmerthatthere mayoccur an
exceptionsoitisbetterforthe programmerto provide the exceptionhandlingcode sothatnormal flow canbe
maintained.
ExceptionHandlingismainlyused tohandle the checkedexceptions.If there occursanyuncheckedexceptionsuchas
NullPointerException,itisprogrammersfaultthathe isnot performingcheckupbefore the code beingused.
Followingisanexampleof anincorrectprogram thattriesto throw an exceptionthatitdoesnotcatch. Because the
program doesnotspecifya throwsclause to declare thisfact,the program will notcompile.
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
To make thisexample compile,youneedtomake twochanges.
First,youneedto declare that throwOne()throwsIllegalAccessException.
Second,main( )mustdefine atry/catchstatementthatcatchesthisexception.
12. Page 12 of 13
The correctedexample isshownhere:
// This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Here is the outputgeneratedbyrunningthisexample program:
inside throwOne
caught java.lang.IllegalAccessException: demo
Differencebetweenthrowandthrows:
1)throwis usedtoexplicitlythrowanexception. throwsisusedto declare an exception.
2)checkedexceptioncannotbe propagatedwithoutthrows. checkedexceptioncanbe propagatedwiththrows.
3)throwis followedbyaninstance. throwsisfollowedbyclass.
4)throwis usedwithinthe method. throwsisusedwiththe methodsignature.
5)You cannotthrow multipleexception You can declare multipleexceptione.g.
publicvoidmethod()throwsIOException,SQLException.
Custom Exception :
If you are creating your own Exception that is known as custom exception or user-defined exception.
1. //Example of custom exception
2.
3. class InvalidAgeException extends Exception{
4. InvalidAgeException(String s){
5. super(s);
6. }
7. }
8. class Excep13{
9.
10. static void validate(int age)throws InvalidAgeException{
11. if(age<18)
12. throw new InvalidAgeException("not valid");
13. else
14. System.out.println("welcome to vote");
15. }
16.
17. public static void main(String args[]){
18. try{
19. validate(13);
20. }catch(Exception m){System.out.println("Exception occured: "+m);}
21.
13. Page 13 of 13
22. System.out.println("rest of the code...");
23. }
24. }
Output:Exception occured: InvalidAgeException:not valid
rest of the code...
Unchecked Exceptions
Those exceptions,thatneednotbe includedinanymethod’sthrows listare calleduncheckedexceptionsbecausethe
compilerdoesnotcheckto see if a methodhandlesorthrowsthese exceptions.
Examples:
Exception Meaning
ArithmeticException Arithmeticerror,suchas divide-by-zero.
ArrayIndexOutOfBoundsException Array index isout-of-bounds.
ArrayStoreException Assignmenttoanarray elementof anincompatibletype.
ClassCastException Invalidcast.
IllegalArgumentException Illegal argumentusedtoinvoke amethod.
IllegalMonitorStateException Illegal monitoroperation,suchaswaitingonanunlockedthread.
IllegalStateException Environmentorapplicationisinincorrectstate.
IllegalThreadStateException Requestedoperationnotcompatible withcurrentthreadstate.
IndexOutOfBoundsException Some type of index isout-of-bounds.
NegativeArraySizeException Array createdwitha negative size.
and more….
Checked Exceptions
Those exceptionsdefinedinjava.langthatmustbe includedinamethod’sthrowslistif thatmethodcangenerate one of
these exceptionsanddoesnothandle ititself.
Examples:
Exception Meaning
ClassNotFoundException Classnot found.
CloneNotSupportedException Attempttoclone an objectthat doesnotimplementtheCloneableinterface.
IllegalAccessException Accessto a class isdenied.
InstantiationException Attempttocreate an objectof an abstract classor interface.
InterruptedException One threadhas beeninterruptedbyanotherthread.
NoSuchFieldException A requestedfielddoesnotexist.
NoSuchMethodException A requestedmethoddoesnotexist.