EXCEPTION HANDLING
Runtime stack mechanism
Default Exception Handling
Exception Hierarchy
Customized Exception handling
Control flow -try catch
Print Exception info
Multiple catch blocks
Finally block
Final , finally and finalize
Control flow -try catch finally
Control flow -nested try catch finally
Possible combinations of try catch finally
Throw
Throws
Exception handling keywords
Compile time errors in exception handling
Customized defined exceptions
1.7 version enhancements
Try with resources
Multi catch block
Exception
An unexcepted unwanted event that disturbs the normal flow of the program is called exception.
Example-File not found exception, SQL Exception
Purpose - Main objective of exception handling is graceful termination of the pgm
Meaning- Not repairing exception. We have to provide alternatively to continue rest of the prgm
normally .
Ex.
Our programming req -read remote file located in London and if it is not available, it shud not be
terminated abnormally.
We shud Provide loc file To continue rest of the prgm normally, it is way of defining alternative is
nothing but exception handling.
Try{ read data from remote file located at London}
Catch(Filenot found exception){use local file and continue rest of the pgm normally}
Runtime stack mechanism
For every thread, jvm creates one runtimestack, for every method by thread will be stored in
corresponding stack.
Each entry is activation record or stack frame
After performing every call,stack will be empty and destroyed by jvm before terminating the thread
If something goes wrong here,by default, java handles the exception and called default exception
handling .
Default Exception Handling
1.Method where exception occurs, that method is responsible to create exception object
including(name,desc,location) and Handovers to jvm.jvm will ck wtr any handling code
2. if no handling code terminte that method abnormally and remove from stack and go to calling
method goes till main method() , if no handling code terminte that main abnormally and remove s
entry from stack
Now jvm call or handovers to default exception handler
default exception handler ,print exception to the console
And terminate pgm abnormally
Exception in thread main :
java.lang.AE/div by zero at Test domorestuff()
at dostuff() at main()
Exception in thread “xxx” name of Exception : Desc
Stack trace
Exception Hierarchy
Root :
Throwable [acts as root in java exception hierarchy]
Exception Ex: file not found exception
Caused by program
Recoverable
Error ex: out of memory
not Caused by program but due to lack of resources
not recoverable
programmer cannot do anything.system admin is responsible to increase heap mem.
…..
Exception Error
RuntimeException VMError
AE, Stackoverflow
NPE Outofmemory
class cast exception Assertionerror
,IoOBE(Array,String), exceptionininitializerError
IllegealArgument E etc….
Number format E
IO exception
EOF E
Filenotfound
InteruptedIO
Servlet exception
Remote exception
Interupted Exceptuion
Checked Exception Vs Un Checked Exception
Checked Exception Exceptions checked by compiler for smooth execution of the program at
runtime.shud be handle by catch or throws
Checked unchecked
Excep checked by compiler for smooth Exceptions which are not checked by compiler
execution of the program are called checked wtr pgrmer handling or not such type of
exceptions excepitons are called unchecked exception.ex;
Ex-Filenotfoundexception etc. arithmetic exception etc
If there is chance of raising checked exception
it shud be handle checked exception either by
try catch or throws keyword otherwise we will
get compile time error
Wtr checked or unchecked every exc occurs at runtime only. No chance of occurring at compile time.
All errors and its child are unchecked
Run time exdceptions and its child classes are unchecked
Except these remaining are checked
A checked ex is fully checked if and only if all its child classes are also checked.
ex io exception,interrupted exception
A checked ex is partially checked if and only if some of its child classes are unchecked.
ex- Exception,throwable(only these two are partially)
Decribe beh of foll exceptions
---------------….
IOException CF
RuntimeException UC
Interrupted exception CF
Error UC
Throwable PC
Arithmetic Exception UC
NullPointer Exception UC
Exception PC
Filenot found exception CF
Customized exception handling using try catch
………………………………………………………………………..
The code which may raise exception is risky code and we have to define that in try block and
handling code in catch block
Try{Riscky code}
Catch {handling code}
Control flow in try catch
…………………………………….
Try{
S1
S2
S3
Catch(x e)
s4;}
S5;
Case 1
1,2,3,5 NT
Case 2 exception in s2 catch block matched
1,4,5 NT
Case 3 exception in s2 no catch block matched
1, abnormal T
Case 4 exception in s4 or s5
Always abnormal T
Note-
1.Within try block anywhere exception, rest of the try block wont execute even though we handle
the exception hence within the try block we have to take only risky code and len shud be as less as
possible
2. In addition to try block there may be a chanc epof exception inside catch and finally blocks
3. If any statement which is not part of try block,and raises exception then it is always abnormal
termination
Methods to print exception information
……………………………………………………………..
e.printTrackTrace()- internally default handler use this to print to console
Name of Exception:Desc,stack trace
Java.lang.AE:/ by zero at Test main()
Sop(e.toString()) or sop(e)
Name of Exception:Desc,
Sop(e.getmessage())
Desc
Try with multiple catch blocks
Is possible and recommended to use
Order of catch block-child and then super class
Otherwise we will get compile time error
Final/finally/finalize
……………………………..
Final -modifier for variable ,method,class
Variable- cannot reassign
Method- cannot override
Class- cannot inherit or extend from this
Finally block always associated with try catch to maintain cleanup code.
Finalize-always invoked by gc just before destroying an object to perform cleanup activities.once
finalize method complets imm gc destroy the object.
Finaly cleanupcode related to try catch.
Finalize clenup activities related to object.whatever resources associated with obj will be deallocated
before dest by using finalize method.
Various possible combinations of try catch finally
……………………………………………………………….
\
1.In try catcth finally,order is important
2.in try, it is mandatory catch or finally otherwise compiletime error that is try without catch or
finally is invalid
3.whnever catch block, try is necessary.catch without try is invalid
4.whenever we fibnally block,try is necessary.finally without try is invalid
5.inside try ,catch and finally blocks, we can declare try catch and finally blocks. That is nesting of try
catch finally is allowed.
6.for t,c anf curly braces are necessary
Throw and throws
……………………………
Throw keyword
1.Order is important in try catch block
2.Whenever try , catch or finally is required else compiletime err
3.whenever catch, try is req.
4.finally block, try is required.
5.insisde try , catch anfd finally blocks can be declared ie. Nesting of try catch finally is allowed.
6.curly braces are mandatory
Throw/throws
…………………….
Pgmer throw exception obj to JVM
Class test{
Psvm(){
throw new AE(:/by zero”);
Sometimes we can create exception and handover to jvm manually and for this we have to use
throw keyword
Main objective of throw keyword is to handover created object to jvm manually.
In first pgm, main method is responsible to create exception obj and handover to jvm
In sec pgm, prgmer create explicitly and handover to jvm manually.
Best use of throw is for user defined exceptions.
Case 1;
Throw e
If e refers null, then we will get nullpoinr exceptioon
Case 2:
First pgm RE AE / by zero
2nd pgm
………….
After throw we are not allowed to write any stmt directly.otherwise we
Will get unreachable stmt comile time error
Case 3:
Throw only throwable objects. Not normal objects
CE:incompatible types.found test req j.l.throwable
Throws keyword
If there is a possibility of raising checked exception, then e=we shud handle checked exception
otherwise we will get CE saying unreported exception xxx must be caught
We can handle this comiple time err using two ways.
First way using try catch
second way using throws keyword
We can use throws to delegate resp to the caller.then caller method(another method or jvm)
Then caller method is resp. to hanle that exception
Throws only for CheckedE
Only to convince compiler
Throws Do1es not prevent abnormal termination of the program
Atleast one throw statement, code wont compile.
1.delegate resp of exc handling to caller(meth or jvm)
2.only for checked exception.
3.only to convince compiler and don’t avoid abnormal termination
.Recommended to use try catch over throws keyword.
a.Throws for class is invalid.can use for methods and constructors.
b.throws only for throwable types.if we try for normal java classes,then we will get compile time
error saying incompatible types
If there is no chance of exception, then we cannot write catch block for that exception.otherwise we
will get comp error saying “ Exception xxx is never thrown in body of correspong\ding try statement.
But rule is applicable only for fully checked exception
Customized exception
………………………………..
Try . to maintain risky code
Catch To maintain exception handling code
Finally to maintain cleanup code
Throw to handover our cereated exception object to the jvm manually
Throws to delegate resp. of creation handling to the caller
Various possible Compile time err in exc handling
Customized or user defined exception
Sometimes to meet prgming requirement we can define our own exc ,such type exception are
customized or user defined exception
Example- too young ,too old , insufficient funds ex
How to deifn own exception
………………………………………
Class TooYoungExdeption extends RunTimeExcepton
TooYoungException(String s)
{Super(s); }
Class ToooldException(String s){super(s);
}]
Defining Customized exception
……………………………………………..
Class custExceptionDemo
{psvm(String a){
Int age =Integer.parseInt(a[]);
If (age>60){
Throw new TooYoungException
(“Pls wait”);
Else if(age<18)
{ Throw new ToooldException(“Pls wait”);
Else{sop(“u will get mail soon”);}
Note1-
Throw keywor best for user defined excepion but not for predefined exception
Highly recommed to define cust exc as unchecked that is we have to extends runtimeexdeption but
not Exception.
To make desc available to default exception handler,super is used.
……………………….
Progrmmer /api developer exception
All exceptions are divided to two categories
a.JVM exception – Exceptions raised automatically by JVM whenever paticular evemnt occurs are
called JVM /exceptions Example.arithmetic ,nullpointer,etc..
b.Programatic exception-exceptions raised excplicitly either by progmer or api devepoler to indicate
that something goes wrong are called programatic exceptions
ex-tooold exception,illegaal argument excpretion etc.
top ten exception
………………………….
1.Arrayindexoutofbound exception -unchecked
Child of indexoutofbound/child of runtimeexception and hence it is unchecked
Raised automatically by jvm whenever trying to access array element with out of range index
2.Nullpointer exception\
child of runtimeexception and hence it is unchecked
Raised automatically by jvm whenever trying to perform any operation on null
String s=null;sopln(s.length());RE:NullPointerException
3.Classcastexception
child of runtimeexception and hence it is unchecked
String s=new String(“d”);
Object 0=(Object)s;
Object o=new Object();
String s=(String)o;
RE: ClassCastException
Parent to child cast will raise classcastexception.
Object o=new String(“”);
String =(String)o;
4.Stackoverflowerror
Child of Error and so unchecked.raised automatically by jvm whenever try to perform recursive
method call.
5.NoClassDefFoundError
Child of Error and so unchecked
If jvm unable to find the class throws NoClassDefFoundError
Raised automatically bu jvm whenever jvm unable to find req .class file
Ex.Java test.
If test not available, then we will get run time exception saying, NoClassdefFoundError:Test
6.ExceptionInInitializerError
Child class of error .and hence unchecked.raised automaticalay by jvm.if any exception occurs by
executing static variable assignmet and static blocks
7.IllegalArgumentException
child of runtimeexception and hence it is unchecked
raised explicitly either by prgmer or by api dev to indicate that the method has been invoked with
illegal argument.
Ex- valid range of thread priorities is 1 to 10. If we r tring o set priority with any othe rvalus, we will
get runtimex exception saying illegal argument exception.
Thread T=new Thread ()
t.setpriority(7);
t.setpriority(15);RE:illegal argument exceptiom
8.Numberformat Exception
Int i=Integer.parseint(“10”);
Int i=Integer.parseint(“ten”);
Unchecked -bcos child of illegalargument which is the child of runtime exception.
Raised explicitly either by prgmer or api developer to indiacte that we are trying to convert string to
number and string is not properly formatted.
Int i=Integer.parseInt(“ten”); RE:numberFromatExxception
9.IllegalStateException
Unchecked -bcos child of runtime exception.
Raised explicitly either by prgmer or api developer to that mewthod has been invojkesd at wrong
time.
After starting of a thred we are not allowed to restart same thread.otherswidse wewill get runtie
exception
10. AssertionError
Child class of error .and hence unchecked.
Raised expkivcitlyy buy the programmer to indicate asssert stmt failed
If x!>10 runtime exception sauying assertion error