SlideShare a Scribd company logo
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.
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
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:
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.
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...
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
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...
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;
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();
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:
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.
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.
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.

More Related Content

PDF
Class notes(week 8) on exception handling
DOCX
Exception handling in java
PDF
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
PDF
Java unit3
PDF
Best Practices in Exception Handling
PPT
Comp102 lec 10
PPTX
Exceptions in Java
PPT
Exception Handling Java
Class notes(week 8) on exception handling
Exception handling in java
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
Java unit3
Best Practices in Exception Handling
Comp102 lec 10
Exceptions in Java
Exception Handling Java

What's hot (20)

PDF
Exception handling
PPTX
Java Exception Handling
PDF
Java Pitfalls and Good-to-Knows
DOCX
Exceptions handling notes in JAVA
PPT
12 exception handling
PPT
Java: Exception
ODP
Exception Handling In Java
PPT
Exception handling in java
PPT
Exception handling
PPTX
Exception handling in java
PPTX
Z blue exception
PPTX
Exception handling
PPT
Exception handling
PPSX
How to handle exceptions in Java Technology
PPTX
Exception Handling
PDF
Java exception-handling
PPTX
Chapter 5
PPTX
Exception handling in ASP .NET
PPT
Exceptionhandling
PPT
Exception handling
Exception handling
Java Exception Handling
Java Pitfalls and Good-to-Knows
Exceptions handling notes in JAVA
12 exception handling
Java: Exception
Exception Handling In Java
Exception handling in java
Exception handling
Exception handling in java
Z blue exception
Exception handling
Exception handling
How to handle exceptions in Java Technology
Exception Handling
Java exception-handling
Chapter 5
Exception handling in ASP .NET
Exceptionhandling
Exception handling
Ad

Similar to Class notes(week 8) on exception handling (20)

PPT
A36519192_21789_4_2018_Exception Handling.ppt
PPT
8.Exception handling latest(MB).ppt .
PDF
Ch-1_5.pdf this is java tutorials for all
PPT
Exception Handling Exception Handling Exception Handling
PPTX
Exception handling in java
PPTX
Java-Unit 3- Chap2 exception handling
PPTX
Chap2 exception handling
PPTX
Exception handling and throw and throws keyword in java.pptx
PPTX
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
PPTX
L14 exception handling
PPTX
Interface andexceptions
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PPT
Exceptions
PDF
Java unit 11
PPTX
java exception.pptx
PPTX
Java Exceptions and Exception Handling
PPTX
Exceptionhandling
DOCX
Java Exception handling
A36519192_21789_4_2018_Exception Handling.ppt
8.Exception handling latest(MB).ppt .
Ch-1_5.pdf this is java tutorials for all
Exception Handling Exception Handling Exception Handling
Exception handling in java
Java-Unit 3- Chap2 exception handling
Chap2 exception handling
Exception handling and throw and throws keyword in java.pptx
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
Java Exception Handling & IO-Unit-3 (1).ppt
L14 exception handling
Interface andexceptions
unit 4 msbte syallbus for sem 4 2024-2025
Exceptions
Java unit 11
java exception.pptx
Java Exceptions and Exception Handling
Exceptionhandling
Java Exception handling
Ad

More from Kuntal Bhowmick (20)

PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
PDF
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
PPT
1. introduction to E-commerce
DOCX
Computer graphics question for exam solved
PDF
DBMS and Rdbms fundamental concepts
PDF
Java questions for interview
PDF
Java Interview Questions
PDF
Operating system Interview Questions
PDF
Computer Network Interview Questions
PDF
C interview questions
PDF
C question
PDF
Distributed operating systems cs704 a class test
DOCX
Cs291 assignment solution
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
1. introduction to E-commerce
Computer graphics question for exam solved
DBMS and Rdbms fundamental concepts
Java questions for interview
Java Interview Questions
Operating system Interview Questions
Computer Network Interview Questions
C interview questions
C question
Distributed operating systems cs704 a class test
Cs291 assignment solution

Recently uploaded (20)

PDF
composite construction of structures.pdf
PPTX
Geodesy 1.pptx...............................................
PPTX
Practice Questions on recent development part 1.pptx
PPTX
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
PPTX
OOP with Java - Java Introduction (Basics)
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPT
Project quality management in manufacturing
PPT
Chapter 6 Design in software Engineeing.ppt
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
Geotechnical Engineering, Soil mechanics- Soil Testing.pdf
PPT
Drone Technology Electronics components_1
PDF
Monitoring Global Terrestrial Surface Water Height using Remote Sensing - ARS...
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
CH1 Production IntroductoryConcepts.pptx
composite construction of structures.pdf
Geodesy 1.pptx...............................................
Practice Questions on recent development part 1.pptx
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
OOP with Java - Java Introduction (Basics)
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
bas. eng. economics group 4 presentation 1.pptx
Project quality management in manufacturing
Chapter 6 Design in software Engineeing.ppt
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Geotechnical Engineering, Soil mechanics- Soil Testing.pdf
Drone Technology Electronics components_1
Monitoring Global Terrestrial Surface Water Height using Remote Sensing - ARS...
Model Code of Practice - Construction Work - 21102022 .pdf
Operating System & Kernel Study Guide-1 - converted.pdf
CH1 Production IntroductoryConcepts.pptx

Class notes(week 8) on exception handling

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