Exception Handling
Exception Handling
Exception Hierarchy
Finally block
Throw
Throws
Exception
An unexcepted unwanted event that disturbs the normal flow of the program is called exception.
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.
Catch(Filenot found exception){use local file and continue rest of the pgm normally}
For every thread, jvm creates one runtimestack, for every method by thread will be stored in
corresponding stack.
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 .
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
at dostuff() at main()
Stack trace
Exception Hierarchy
Root :
Caused by program
Recoverable
not recoverable
…..
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
Wtr checked or unchecked every exc occurs at runtime only. No chance of occurring at compile time.
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.
---------------….
IOException CF
RuntimeException UC
Interrupted exception CF
Error UC
Throwable PC
Arithmetic Exception UC
NullPointer Exception UC
Exception PC
………………………………………………………………………..
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}
…………………………………….
Try{
S1
S2
S3
Catch(x e)
s4;}
S5;
Case 1
1,2,3,5 NT
1,4,5 NT
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
……………………………………………………………..
Sop(e.toString()) or sop(e)
Name of Exception:Desc,
Sop(e.getmessage())
Desc
Final/finally/finalize
……………………………..
Finally block always associated with try catch to maintain cleanup code.
Finalize clenup activities related to object.whatever resources associated with obj will be deallocated
before dest by using finalize method.
……………………………………………………………….
\
2.in try, it is mandatory catch or finally otherwise compiletime error that is try without catch or
finally 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.
……………………………
Throw keyword
5.insisde try , catch anfd finally blocks can be declared ie. Nesting of try catch finally is allowed.
Throw/throws
…………………….
Psvm(){
Sometimes we can create exception and handover to jvm manually and for this we have to use
throw keyword
In first pgm, main method is responsible to create exception obj and handover to jvm
Case 1;
Throw e
Case 2:
First pgm RE AE / by zero
2nd pgm
………….
Case 3:
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.
We can use throws to delegate resp to the caller.then caller method(another method or jvm)
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.
Customized exception
………………………………..
Sometimes to meet prgming requirement we can define our own exc ,such type exception are
customized or user defined exception
………………………………………
Class TooYoungExdeption extends RunTimeExcepton
TooYoungException(String s)
{Super(s); }
}]
……………………………………………..
Class custExceptionDemo
{psvm(String a){
If (age>60){
(“Pls wait”);
Else if(age<18)
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.
……………………….
a.JVM exception – Exceptions raised automatically by JVM whenever paticular evemnt occurs are
called JVM /exceptions Example.arithmetic ,nullpointer,etc..
………………………….
Raised automatically by jvm whenever trying to access array element with out of range index
2.Nullpointer exception\
String s=null;sopln(s.length());RE:NullPointerException
3.Classcastexception
Object 0=(Object)s;
String s=(String)o;
RE: ClassCastException
4.Stackoverflowerror
Child of Error and so unchecked.raised automatically by jvm whenever try to perform recursive
method call.
5.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
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.
t.setpriority(7);
8.Numberformat Exception
Int i=Integer.parseint(“10”);
Int i=Integer.parseint(“ten”);
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.
9.IllegalStateException
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.