Exception Handling
Exception Handling
ExceptionHandlinginJava Whathappensbehindthecodeintdata=50/0?
Whyusemultiplecatchblock?
Theexceptionhandlinginjavaisoneofthepowerfulmechanism to
Isthereanypossibilitywhenfinallyblockisnotexecuted?
handle the runtime errors so that normal flow of the application can
Whatisexceptionpropagation?
bemaintained.
Whatisthedifferencebetweenthrowandthrowskeyword?
In this page, we will learn about java exception, its type and the
What are the 4 rules for using exception handling with method
differencebetweencheckedanduncheckedexceptions.
overriding?
Whatisexception
HierarchyofJavaExceptionclasses
DictionaryMeaning:Exceptionisanabnormalcondition.
Whatisexceptionhandling
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFound,IO,SQL,Remoteetc.
AdvantageofExceptionHandling
1. statement1
2. statement2
3. statement3
4. statement4
5. statement5//exceptionoccurs TypesofException
6. statement6
There are mainly two types of exceptions: checked and unchecked
7. statement7
where error is considered as unchecked exception. The sun
8. statement8
microsystemsaystherearethreetypesofexceptions:
9. statement9
[Link]
Suppose there is 10 statements in your program and there occurs an [Link]
exception at statement 5, rest of the code will not be executed i.e.
[Link],rest
of the statement will be executed. That is why we use exception Difference between checked and
handlinginjava.
uncheckedexceptions
1)CheckedException
DoYouKnow?
Page 1 of 15
TheclassesthatextendThrowableclassexceptRuntimeExceptionand 1. inta[]=newint[5]
[Link],SQLException
Elite Creations 2. a[10]=50//ArrayIndexOutOfBoundsException
[Link].
2)UncheckedException
JavaExceptionHandlingKeywords
The classes that extend RuntimeException are known as unchecked
Thereare5keywordsusedinjavaexceptionhandling.
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not [Link]
checkedatcompiletimerathertheyarecheckedatruntime.
[Link]
3)Error [Link]
[Link]
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
[Link]
AssertionErroretc.
1)ScenariowhereArithmeticExceptionoccurs
Ifwedivideanynumberbyzero,thereoccursanArithmeticException.
1. inta=50/0//ArithmeticException
2)ScenariowhereNullPointerExceptionoccurs
Ifwehavenullvalueinanyvariable,performinganyoperationbythe
variableoccursanNullPointerException.
1. Strings=null
2. [Link]([Link]())//NullPointerException
3)ScenariowhereNumberFormatExceptionoccurs
1. Strings="abc"
2. inti=[Link](s)//NumberFormatException
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsExceptionasshownbelow:
Page 2 of 15
ContentMenu There can be 100 lines of code after exception. So all the code after
Elite Creations exceptionwillnotbeexecuted.
Javatrycatch
Solutionbyexceptionhandling
Javatryblock Let'sseethesolutionofaboveproblembyjavatrycatchblock.
Java try block is used to enclose the code that might throw an 1. publicclassTesttrycatch2{
[Link]. 2. publicstaticvoidmain(Stringargs[]){
Javatryblockmustbefollowedbyeithercatchorfinallyblock. 3. try{
4. intdata=50/0
Syntaxofjavatrycatch 5. }catch(ArithmeticExceptione){[Link](e)}
6. [Link]("restofthecode...")
1. try{ 7. }
2. //codethatmaythrowexception 8. }
3. }catch(Exception_class_Nameref){}
TestitNow
Output:
Syntaxoftryfinallyblock
[Link]:/byzero
1. try{ restofthecode...
2. //codethatmaythrowexception
3. }finally{} Now,asdisplayedintheaboveexample,restofthecodeisexecuted
[Link]...statementisprinted.
Javacatchblock
Internalworkingofjavatrycatchblock
[Link]
thetryblockonly.
Youcanusemultiplecatchblockwithasingletry.
Problemwithoutexceptionhandling
Let'strytounderstandtheproblemifwedon'tusetrycatchblock.
1. publicclassTesttrycatch1{
2. publicstaticvoidmain(Stringargs[]){
3. intdata=50/0//maythrowexception
4. [Link]("restofthecode...")
5. }
6. }
TestitNow The JVM firstly checks whether the exception is handled or not. If
exception is not handled, JVM provides a default exception handler
Output:
thatperformsthefollowingtasks:
Printsoutexceptiondescription.
[Link]:/byzero
Prints the stack trace (Hierarchy of methods where the
exceptionoccurred).
As displayed in the above example, rest of the code is not executed
(insuchcase,restofthecode...statementisnotprinted). Page 3 of 15 Causestheprogramtoterminate.
But if exception is handled by the application programmer, normal ContentMenu
[Link].
Elite Creations
Javacatchmultipleexceptions
prev next
JavaMulticatchblock
Share 22
If you have to perform different tasks at the occurrence of different
Exceptions,usejavamulticatchblock.
Let'sseeasimpleexampleofjavamulticatchblock.
1. publicclassTestMultipleCatchBlock{
2. publicstaticvoidmain(Stringargs[]){
3. try{
4. inta[]=newint[5]
5. a[5]=30/0
6. }
7. catch(ArithmeticException e)
{[Link]("task1iscompleted")}
8. catch(ArrayIndexOutOfBoundsException e)
{[Link]("task2completed")}
9. catch(Exception e)
{[Link]("commontaskcompleted")}
10.
11. [Link]("restofthecode...")
12. }
13. }
TestitNow
Output:task1completed
restofthecode...
Rule:Allcatchblocksmustbeorderedfrommostspecificto
most general i.e. catch for ArithmeticException must come
beforecatchforException.
1. classTestMultipleCatchBlock1{
2. publicstaticvoidmain(Stringargs[]){
3. try{
4. inta[]=newint[5]
5. a[5]=30/0
6. }
7. catch(Exception e)
Page 4 of 15 {[Link]("commontaskcompleted")}
8. catch(ArithmeticException e) ContentMenu
{[Link]("task1iscompleted")}
Elite Creations
9. catch(ArrayIndexOutOfBoundsException
{[Link]("task2completed")}
e)
JavaNestedtryblock
10. [Link]("restofthecode...")
Thetryblockwithinatryblockisknownasnestedtryblockinjava.
11. }
12. } Whyusenestedtryblock
TestitNow Sometimes a situation may arise where a part of a block may cause
[Link]
Output:
cases,exceptionhandlershavetobenested.
Compiletimeerror
Syntax:
1. ....
3. {
4. statement1
Share 5
5. statement2
6. try
7. {
8. statement1
9. statement2
10. }
11. catch(Exceptione)
12. {
13. }
14. }
15. catch(Exceptione)
16. {
17. }
18. ....
Javanestedtryexample
Let'sseeasimpleexampleofjavanestedtryblock.
1. classExcep6{
2. publicstaticvoidmain(Stringargs[]){
3. try{
4. try{
5. [Link]("goingtodivide")
6. intb=39/0
7. }catch(ArithmeticExceptione){[Link](e)}
8.
9. try{
10. inta[]=newint[5]
14. [Link]("otherstatement)
Javafinallyblock
15. }catch(Exceptione){[Link]("handeled")} Javafinallyblockisablockthatisusedtoexecuteimportantcode such as
16. closingconnection,streametc.
17. [Link]("normalflow..")
Javafinallyblockisalwaysexecutedwhetherexceptionishandledornot.
18. }
Javafinallyblockfollowstryorcatchblock.
19. }
prev next
Share 11
Note:Ifyoudon'thandleexception,beforeterminatingtheprogram,
JVMexecutesfinallyblock(ifany).
Whyusejavafinally
Finallyblockinjavacanbeusedtoput"cleanup"codesuchasclosing
afile,closingconnectionetc.
UsageofJavafinally
Let'sseethedifferentcaseswherejavafinallyblockcanbeused.
Case1
Let'sseethejavafinallyexamplewhereexceptiondoesn'toccur.
Page 6 of 15
1. classTestFinallyBlock{ 7. catch(ArithmeticExceptione){[Link](e)}
2. publicstaticvoidmain(Stringargs[]){
Elite Creations 8. finally{[Link]("finallyblockisalwaysexecuted")}
3. try{ 9. [Link]("restofthecode...")
4. intdata=25/5 10. }
5. [Link](data) 11. }
6. }
TestitNow
7. catch(NullPointerExceptione){[Link](e)}
8. finally{[Link]("finallyblockisalwaysexecuted")} Output:[Link]:/byzero
9. [Link]("restofthecode...") finallyblockisalwaysexecuted
10. } restofthecode...
11. }
TestitNow
Rule:Foreachtryblocktherecanbezeroormorecatchblocks,but
Output:5 onlyonefinallyblock.
finallyblockisalwaysexecuted
restofthecode...
Note: The finally block will not be executed if program exits(either
by calling [Link]() or by causing a fatal error that causes the
Case2 processtoabort).
Let's see the java finally example where exception occurs and not
handled.
prev next
1. classTestFinallyBlock1{
2. publicstaticvoidmain(Stringargs[]){
Share 5
3. try{
4. intdata=25/0
5. [Link](data)
6. }
7. catch(NullPointerExceptione){[Link](e)}
8. finally{[Link]("finallyblockisalwaysexecuted")}
9. [Link]("restofthecode...")
10. }
11. }
TestitNow
Output:finallyblockisalwaysexecuted
[Link]:/byzero
Case3
Let'sseethejavafinallyexamplewhereexceptionoccursandhandled.
1. publicclassTestFinallyBlock2{
2. publicstaticvoidmain(Stringargs[]){
3. try{
4. intdata=25/0
5. [Link](data)
6. }
Page 7 of 15
ContentMenu ContentMenu
Elite Creations
Javathrowexception JavaExceptionpropagation
An exception is first thrown from the top of the stack and if it is not
Javathrowkeyword caught,itdropsdownthecallstacktothepreviousmethod,Ifnotcaught
there,theexceptionagaindropsdowntothepreviousmethod,andsoon
TheJavathrowkeywordisusedtoexplicitlythrowanexception. until they are caught or until they reach the very bottom of the call
[Link].
We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom
[Link]. Rule: By default Unchecked Exceptions are forwarded in calling
chain(propagated).
Thesyntaxofjavathrowkeywordisgivenbelow.
ProgramofExceptionPropagation
1. throwexception
1. classTestExceptionPropagation1{
Let'sseetheexampleofthrowIOException.
2. voidm(){
3. intdata=50/0
1. thrownewIOException("sorrydeviceerror)
4. }
5. voidn(){
javathrowkeywordexample 6. m()
7. }
In this example, we have created the validate method that takes
8. voidp(){
integer value as a parameter. If the age is less than 18, we are
throwing the ArithmeticException otherwise print a message welcome 9. try{
11. }catch(Exceptione){[Link]("exceptionhandled")}
1. publicclassTestThrow1{ 12. }
2. staticvoidvalidate(intage){ 13. publicstaticvoidmain(Stringargs[]){
3. if(age<18) 14. TestExceptionPropagation1obj=newTestExceptionPropagation1()
4. thrownewArithmeticException("notvalid") 15. obj.p()
5. else 16. [Link]("normalflow...")
6. [Link]("welcometovote") 17. }
7. } 18. }
8. publicstaticvoidmain(Stringargs[]){
9. validate(13) TestitNow
10. [Link]("restofthecode...")
Output:exceptionhandled
11. } normalflow...
12. }
TestitNow
Output:
[Link]:notvalid
prev next
Page 8 of 15
Share 9
In the above example exception occurs in m() method where it is not ContentMenu
handled,so it is propagated to previous n() method where it is not
Elite Creations
handled,againitispropagatedtop()methodwhereexceptionishandled.
Javathrowskeyword
Exception can be handled in any method in call stack either in main()
method,p()method,n()methodorm()method. TheJavathrowskeyword is used to declare an exception. It gives an information
to the programmer that there may occur an exception so it is better for the
programmer to provide the exception handling code so that normal flow can be
Rule:Bydefault,CheckedExceptionsarenotforwardedincalling maintained.
chain(propagated).
[Link]
any unchecked exception such as NullPointerException, it is programmers fault that
Program which describes that checked exceptions are not
heisnotperformingcheckupbeforethecodebeingused.
propagated
1. classTestExceptionPropagation2{ Syntaxofjavathrows
2. voidm(){
3. [Link]("deviceerror")//checkedexception 1. return_typemethod_name()throwsexception_class_name{
4. } 2. //methodcode
5. voidn(){ 3. }
6. m()
7. }
Whichexceptionshouldbedeclared
8. voidp(){
9. try{ Ans)checkedexceptiononly,because:
10. n()
uncheckedException:underyourcontrolsocorrectyourcode.
11. }catch(Exceptione){[Link]("exceptionhandeled")}
error: beyond your control e.g. you are unable to do anything if there occurs
12. }
VirtualMachineErrororStackOverflowError.
13. publicstaticvoidmain(Stringargs[]){
14. TestExceptionPropagation2obj=newTestExceptionPropagation2()
15. obj.p()
AdvantageofJavathrowskeyword
16. [Link]("normalflow") NowCheckedExceptioncanbepropagated(forwardedincallstack).
17. }
Itprovidesinformationtothecallerofthemethodabouttheexception.
18. }
TestitNow
Javathrowsexample
Output:CompileTimeError
Let'sseetheexampleofjavathrowsclausewhichdescribesthatcheckedexceptions
canbepropagatedbythrowskeyword.
1. [Link]
prev next
2. classTestthrows1{
3. voidm()throwsIOException{
Share 5
4. thrownewIOException("deviceerror")//checkedexception
5. }
6. voidn()throwsIOException{
7. m()
8. }
9. voidp(){
10. try{
11. n()
Page 9 of 15 12. }catch(Exceptione){[Link]("exceptionhandled")}
13. } Case2:Youdeclaretheexception
14. publicstaticvoidmain(Stringargs[]){
Elite Creations
15. Testthrows1obj=newTestthrows1() A)Incaseyoudeclaretheexception,ifexceptiondoesnotoccur,thecodewill
beexecutedfine.
16. obj.p()
B)Incaseyoudeclaretheexceptionifexceptionoccures,anexceptionwillbe
17. [Link]("normalflow...")
thrownatruntimebecausethrowsdoesnothandletheexception.
18. }
19. } A)Programifexceptiondoesnotoccur
TestitNow 1. [Link].*
2. classM{
Output:
3. voidmethod()throwsIOException{
4. [Link]("deviceoperationperformed")
exceptionhandled
5. }
normalflow...
6. }
7. classTestthrows3{
Rule: If you are calling a method that declares an exception, you must 8. publicstaticvoidmain(Stringargs[])throwsIOException{//declareexception
eithercaughtordeclaretheexception.
9. Mm=newM()
10. [Link]()
Therearetwocases:
11.
1.Case1:[Link]/catch.
12. [Link]("normalflow...")
2.Case2:[Link].
13. }
14. }
Case1:Youhandletheexception
TestitNow
In case you handle the exception, the code will be executed fine whether
Output:deviceoperationperformed
exceptionoccursduringtheprogramornot.
normalflow...
1. [Link].*
2. classM{ B)Programifexceptionoccurs
3. voidmethod()throwsIOException{
1. [Link].*
4. thrownewIOException("deviceerror")
2. classM{
5. }
3. voidmethod()throwsIOException{
6. }
4. thrownewIOException("deviceerror")
7. publicclassTestthrows2{
5. }
8. publicstaticvoidmain(Stringargs[]){
6. }
9. try{
7. classTestthrows4{
10. Mm=newM()
8. publicstaticvoidmain(Stringargs[])throwsIOException{//declareexception
11. [Link]()
9. Mm=newM()
12. }catch(Exceptione){[Link]("exceptionhandled")}
10. [Link]()
13.
11.
14. [Link]("normalflow...")
12. [Link]("normalflow...")
15. }
13. }
16. }
14. }
TestitNow
TestitNow
Output:exceptionhandled
normalflow... Output:RuntimeException
Page 10 of 15
Differencebetweenthrowandthrows ContentMenu
Elite Creations
Que)Canwerethrowanexception? throwsinJava
Yes,bythrowingsameexceptionincatchblock. There are many differences between throw and throws keywords. A
listofdifferencesbetweenthrowandthrowsaregivenbelow:
Javathrowexample
1. voidm(){
2. thrownewArithmeticException("sorry")
3. }
Javathrowsexample
1. voidm()throwsArithmeticException{
2. //methodcode
3. }
Javathrowandthrowsexample
1. voidm()throwsArithmeticException{
2. thrownewArithmeticException("sorry")
3. }
prev next
Share 7
Page 11 of 15
ContentMenu 8. [Link]()
Elite Creations 9. }}
Javafinalexample
1. classFinalExample{
2. publicstaticvoidmain(String[]args){
3. finalintx=100
4. x=200//CompileTimeError
5. }}
Javafinallyexample
1. classFinallyExample{
2. publicstaticvoidmain(String[]args){
3. try{
4. intx=300
5. }catch(Exceptione){[Link](e)}
6. finally{[Link]("finallyblockisexecuted")}
7. }}
Javafinalizeexample
1. classFinalizeExample{
2. publicvoidfinalize(){[Link]("finalizecalled")}
3. publicstaticvoidmain(String[]args){
4. FinalizeExamplef1=newFinalizeExample()
5. FinalizeExamplef2=newFinalizeExample()
6. f1=null
Page 12 of 15
7. f2=null
ContentMenu 1. [Link].*
Elite Creations 2. classParent{
4. }
MethodOverridinginJava 5.
6. classTestExceptionChild1extendsParent{
There are many rules if we talk about methodoverriding with exception
7. voidmsg()throwsArithmeticException{
[Link]:
8. [Link]("child")
Ifthesuperclassmethoddoesnotdeclareanexception
9. }
If the superclass method does not declare an exception,
10. publicstaticvoidmain(Stringargs[]){
subclass overridden method cannot declare the checked
11. Parentp=newTestExceptionChild1()
exceptionbutitcandeclareuncheckedexception.
12. [Link]()
Ifthesuperclassmethoddeclaresanexception
13. }
If the superclass method declares an exception, subclass
overriddenmethodcandeclaresame,subclassexceptionorno 14. }
exceptionbutcannotdeclareparentexception.
TestitNow
Output:child
If the superclass method does not declare an
exception
Ifthesuperclassmethoddeclaresanexception
1) Rule: If the superclass method does not declare an exception,
subclass overridden method cannot declare the checked
1)Rule:Ifthesuperclassmethoddeclaresanexception,subclass
exception.
overridden method can declare same, subclass exception or no
exceptionbutcannotdeclareparentexception.
1. [Link].*
2. classParent{ Exampleincasesubclassoverriddenmethoddeclares
3. voidmsg(){[Link]("parent")} parentexception
4. }
5. 1. [Link].*
6. classTestExceptionChildextendsParent{ 2. classParent{
7. voidmsg()throwsIOException{ 3. voidmsg()throwsArithmeticException{[Link]("parent")}
8. [Link]("TestExceptionChild") 4. }
9. } 5.
10. publicstaticvoidmain(Stringargs[]){ 6. classTestExceptionChild2extendsParent{
11. Parentp=newTestExceptionChild() 7. voidmsg()throwsException{[Link]("child")}
12. [Link]() 8.
13. } 9. publicstaticvoidmain(Stringargs[]){
14. } 10. Parentp=newTestExceptionChild2()
11. try{
TestitNow
12. [Link]()
Output:CompileTimeError 13. }catch(Exceptione){}
14. }
15. }
2) Rule: If the superclass method does not declare an exception,
subclass overridden method cannot declare the checked TestitNow
exceptionbutcandeclareuncheckedexception.
Output:CompileTimeError
Page 13 of 15
Exampleincasesubclassoverriddenmethoddeclares Exampleincasesubclassoverriddenmethoddeclares
Elite Creations
sameexception noexception
1. [Link].* 1. [Link].*
2. classParent{ 2. classParent{
3. voidmsg()throwsException{[Link]("parent")} 3. voidmsg()throwsException{[Link]("parent")}
4. } 4. }
5. 5.
6. classTestExceptionChild3extendsParent{ 6. classTestExceptionChild5extendsParent{
7. voidmsg()throwsException{[Link]("child")} 7. voidmsg(){[Link]("child")}
8. 8.
9. publicstaticvoidmain(Stringargs[]){ 9. publicstaticvoidmain(Stringargs[]){
14. } 14. }
15. } 15. }
TestitNow TestitNow
Output:child Output:child
Exampleincasesubclassoverriddenmethoddeclares
subclassexception prev next
1. [Link].* Share 12
2. classParent{
3. voidmsg()throwsException{[Link]("parent")}
4. }
5.
6. classTestExceptionChild4extendsParent{
7. voidmsg()throwsArithmeticException{[Link]("child")}
8.
9. publicstaticvoidmain(Stringargs[]){
10. Parentp=newTestExceptionChild4()
11. try{
12. [Link]()
13. }catch(Exceptione){}
14. }
15. }
TestitNow
Output:child
Page 14 of 15
ContentMenu
Elite Creations
JavaCustomException
If you are creating your own Exception that is known as custom
[Link]
tocustomizetheexceptionaccordingtouserneed.
By the help of custom exception, you can have your own exception
andmessage.
Let'sseeasimpleexampleofjavacustomexception.
1. classInvalidAgeExceptionextendsException{
2. InvalidAgeException(Strings){
3. super(s)
4. }
5. }
1. classTestCustomException1{
2.
3. staticvoidvalidate(intage)throwsInvalidAgeException{
4. if(age<18)
5. thrownewInvalidAgeException("notvalid")
6. else
7. [Link]("welcometovote")
8. }
9.
10. publicstaticvoidmain(Stringargs[]){
11. try{
12. validate(13)
13. }catch(Exception m)
{[Link]("Exceptionoccured:"+m)}
14.
15. [Link]("restofthecode...")
16. }
17. }
TestitNow
Output:Exceptionoccured:InvalidAgeException:notvalid
restofthecode...
prev next
Share 2
Page 15 of 15