CH 6 Exception - Handling
CH 6 Exception - Handling
Note:- for every Thread JVM create a seperate stack at the time of Thread creation.
and
all method calls by that thread will be stored in that stack.
each entry in stack is called Activation record or stack frame.
after completing every method call jvm removes the that method calls entry
from stack and
after completing all method calls jvm destroys the emty stack and terminate
prog normally.
1 Name of exception
2 Description of exception
3 Location of the exception (stack trace)
> after creating exception object, the method handovers that object to JVM.
> JVM checks that method contains exception handling code or not.
if not
then jvm terminates that method abnormally(in bad condition/ beech me hai) and
and removes corresponding entry from stack .
Objcet
|
Throwable
Objcet
|
Throwable
|
-----------------------------------------------------------------------------------
-----------------------------
|
|
Exception
Error
|_____________________
_________________________________|____________
| |
| |
----------------------------------------------- VMError
LinkageError AssertationError
| | | | _______|___________
|
RuntimeException IOException SQLException ServletException |
|
| | OutOfMemoryError
StackOverflowError
| |_________
| |--EOFException
|--ArthimeticException |
| |--FileNotFoundException
|--NullPointerException |
| |--InterrptedIOException
|--IndexOutBoundException
| |
| |-ArrayIndexOutOfBoundException
| |-StringIndexOutOfBoundException
|
|--IllegalArgumentException
| |
| |--NumberFormatException
|
|--ClassCastException
|
|--IllegalStateException
Exception :- Most of cases Exceptions are caused by our program and these are
recoverable.
ex: if FileNotFoundException occures then we can use local file and can continue
rest of the prog execution normally.
Error : - most of cases errors are not caused by our program these are due to lack
of system resources and these are non recoverable.
ex: if 'OutOfMemoryError' occurs being a programmer we can not do anything, prog
wil be terminated abnormally.
system/server admin is responsible to raise/increase heap memory.
UNCHECKED EXCEPTION:-
classes that extend RuntimeException are known as unchecked exceptions
e.g.
ArithmeticException,
NullPointerException,
ArrayIndexOutOfBoundsException etc.
Note:- Unchecked exceptions are not checked at compile-time rather they are
checked at runtime.
Note:-RuntimeException and its childs + Errors and its child are un checked and
remaining all are checked Exceptions
ex: IOException
InterruptedException
ex : Exception
the only PARTIIALLY CHECKED Exception in java are:
ex:
Throwable
Exception
try
{
stmt 1;
stmt 2;
stmt 3;
}
catch(X e)
{
stmt 4;
}
stmt 5;
Note:-
CASE 3: if exception raised at stmt 2 but catch block not matched then
1 followed by abnormal termination.
Note:- here, if catch block not matched then below outside stmt also not executed.
Note 1:- Within the try block, if anywhere an exception raised then rest of try
stmt will be executed, even though we handled that exception.
Note 2:- There may be a chance of raising exception inside catch and finally blocks
also , in addition to try block.
ex:
try
{
}
catch(filenotfoundexception e)
{
use local file
}
catch(arthimeticException e)
{
perform these operation
}
catch(SQlException e)
{
dont use sql db use , mysql db
}
catch(Exception e)
{
default handler
}
Note:- if try with multiple catch then order of catch blocks is very important.
it should be child to parent. if opposite then CE.
ex:
try
{
sop(10/0);
}
catch(arthimeticException e)
{
perform these operation
}
catch(Exception e)
{
default handler
}
** FINALLY BLOCK:
----------------
>main objective of finally block is to maintain clean up code.
Note:- the speciality of finally block is it will be executed always irrespective
of wheather the exception raised or not
whether handled or not.
CASE 1-> if try , catch , finally , and if exception is not occurred then try and
finally executed not catch.
CASE 2-> if try , catch , finally , and if exception is occurred then try , catch,
finally executed.
CASE 3-> if try , catch , finally , and if exception occurred and catch block not
matched then try and finally executed
** RETURN VS FINALLY:
---------------------
Note1 :-first finally block executed and after that only return stmt will be
considerd.
Note2 :-if return stmt is written in try block or finally block will executed, but
if write system.exit(0); in try block
then finallu block will not executed but return will executed.
** FINALLY VS SYSTEM.EXIT(0)
----------------------------
There is only one situation where finally block will not be executed if we use
system.exit(0) mehtod.
after using this method jvm itself will be shutdown, and finally block not
executed.
FINAL:
------
Final is the modifier, applicable for classes, methods and variables.
if a class is declared final then child class creation is not possible.
if a method is declared final then overriding of that method is not possible.
if a var is declared final then reassignment is not possible.
FINALLY:
--------
finally is the block with try catch to maintain clean up code which should be
executed always whether exception raised or not
and whether handled or not.
FINALIZE:
---------
finalize is a method, always invoked by Garbage collector just befor destroying an
object to perform cleanup activities.
Note:- finally block meant for clean up activities related- try block
where as
finalize() mehtod meant for clean up activities related to object.
--------------------
Note:-
1 if we are not entering into try block , then finally block will not be executed.
and after entering we can not come out side without executing finally.
2 we can take try catch inside try, nested try catch is possible
3 most specific exception can be handled by using inner try catch and general
exception handled by using outer try catch.
2 : if we write catch then compulsory we should write try- mean without try catch
not allowed.
3 : if we write finally block compulsory we should write try. mean finally without
try is invalid.
5 : with in try catch finally, we can take nested try catch finally,
ex:
try{
}
catch(X e){
} // valid
ex2:
try{
}
catch(X e){
}
catch(Y e){
}
// valid
ex3:
try{
}
catch(X e){
}
catch(X e){
}
// invalid
ex4:
try{
}
catch(X e){
}
finally{
}
// valid
ex5:
try{
}
finally{
}
// valid
ex6:
try{
} // CE:- try wihtout catch or finally not allowed.
ex:7
catch(X e){
} // CE:- catch wihtout try.
ex 8:
finally{}
// CE:- finally without try.
ex 9:
try{
}
sop("hello"); CE:- try without catch finally-[means in middile any stmt not
allowed]
catch(X e){
}
ex 10: // invalid
try{
}
catch(X e){
}
sop("hello");
catch(X e){ CE:- catch without try--[means in middile any stmt not allowed]
}
ex 11: // invalid
try{
}
catch(X e){
}
sop("hello");
finally{ CE:- finally without try--[means in middile any stmt not allowed]
}
ex 12: // invalid
try{
}
finally{
}
catch(X e){ CE:- catch without try--[means in middile order is imp]
}
ex 13: // valid
try{
}
catch(X e){
}
try{
}
finally{
}
ex 14: // invalid
try{
}
catch(X e){
}
finally{
}
finally{ // CE: - finally without try.
}
ex 15: // valid
try{
}
catch(X e){
}
try{
}
catch(Y e1){
}
ex 14: // valid
try{
}
catch(X e){
}
finally{
}
try{
}
catch(Y e2){
}
finally{
}
ex 15: // invalid
try{
}
try{ // CE:- try without catch finally.
}
catch(X e){
}
-------------------------------------------
Note:- Generally we can use throw kw for customized exceptions but not for
predefined exceptions.
CASE 2: after throw stmt , we can not take any stmt directally , then we get CE -
unreachable stmt.
ex: throw new ArthimeticException("\ by zero");
sop("hello");
CASE 3: we can use throw kw only for Throwable type , otherwise we get CE-
incompatible type.
ex:
2 : throws kw required only for checked exception, and usage for unchecked is no
use.
3 : throws kw req only to continue compiler, but it not handle exception, and
throws does not prevent abnormal termination of program.
4 to handle exception we use try catch. so
or
throw is used to explicitly throw an exception from a method.
throws is used in the method signature to declare that a method might throw one or
more exceptions, thereby requiring the caller to handle them.
IMP_NOTE: => In our prog, if there is any chance of raising checked exception
then compulsory we should handle either try catch or by throws kw else
code will not compile.
or
Class Test
{
PSVM() throws InterruptedException
{
Thread.sleep(5000);
}
}
ex:2
-----
try
{
sop(10/0);
}
catch(ArthimeticExceptin e)
{
//
}
Class Test
{
PSVM() throws ArthimeticExceptin
{
sop(10/0);
}
}
**Note:- if we have many mehtod and we handover exception one above one order
then , we can not remove at least one throws kw
then prog will not be execute.
CASE 4:- we can use throws kw only for constructor and methods but not for classes.
some of time, we create our own exception to meet our programming requirments.
such type of exceptions are called customized exceptions.
ex:
1 InsufficientFundsException
2 TooYoungException
3 TooOldException
ex:
if(age>60)
{
throw new TooOld("Yogesh , your time now finish, plz wait for next
birth");
}
else if(age<18)
{
throw new TooYoung("Badri , its your lucky time , plz wait for better
match");
}
else
{
System.out.println("sorry");
}
}
ex:
try{
}
catch(Error e)
{
} // valid
1 : JVM Exceptions
2 : Programmatic Exceptions
1 : JVM Exception:
------------------
The Exceptions which are raised automatically by jvm whenever a particular event
occurs, known as JVM Exception
ex: ArrayIndexOutOfBoundException
NullPointerException
2 : Programatic Exception
-------------------------
The Exception which are raised explicitally by programmer or by API developer is
known as Programmatic Exception.
ex: IllegalArgumentException
1 ArrayIndexOutOfBoundException:
--------------------------------
>child of RuntimeException and its unchecked
>raised automatically by jvm if we try to access array element with out of range.
2 NullPointerException:
-----------------------
>its child of RuntimeException and its unchecked
>raised automatically by jvm, if we try to call any mehtod on null.
3 StackOverFlowError:
---------------------
> it is child of Error and its unchecked. invoked by jvm when recursive mehtod
call.[two methods call to each other]
4 NoClassDefFoundError:
-----------------------
>its child of Error and its unchecked. invoked by jvm automatically if it is unable
to find required .class file.
5 ClassCastException:
---------------------
>its child of RuntimeException and its unchecked, raised by jvm automatically if we
try to type cast parent object to child type.
6 ExceptionInInitiazerError:
----------------------------
> its child of Error and its unchecked , raised by jvm automatically if any
Exception occurs while performing static var initializaiton and static block
execution.
7 IllegalArgumentException :
----------------------------
> its child of RuntimeException and its unchecked, raised explicitally by programer
or by API developer to indicate that a method
has been invoked with inappropriate argument.
8 NumberFormatException :
-------------------------
> its child of IllegalArgumentException and its unchecked, raised explicitally by
programmer or by API developer to indicate that we are attemping to convert string
to number . but string is not properly formatted.
9 IllegalStateException :
------------------------
> its child of RuntimeException and its unchecked. raised explicitally by
programmer or by API developer to indicate that a method has been invoked at
approriate time.
Note:- once session expires , we can not call any method on session object. then we
get this error.
10 AssertationError:
--------------------
> it is child of Error, and its unchecked, raised explicitally by programmer or by
API developer to indicate that Assert stmt fails.
Example Table:
Note:- now from 1.7 - the resources which are opened as part of try block will be
closed automatically once the controle reaches end of try block either normally or
abnormally.
>we are not required to close explicitaally.
>it is not requierd to write finally block explicitally so length of code reduced.
CONCLUSION:-
1 we can declare any no of resources but all these should be seperated with ;
semicolon.
ex:
3 All resources reference vars are implicitally final and we can not perform
reassignment with in try block.
Imp_Note:
ex:
try(r)
{
}
5 The main advantage of try with resources is finally block will become dummy
because we r not required to close resources of explicitally.
The main advantage of this , we can write a single catch block, and which can
handle multiple different exceptions.
try{
}
catch(ArthimeticException | NullPointerException e)
{
e.printStackTrace();
}
catch(ClassCastException | IOExcepiton e )
{
sop(e.getMessage());
}
Note:- in multi catch block, there should not be any relation bw Exception type
(either child to parent or parent to child or same type- else we get CE)
try
{
sop(10/0);
}
catch(ArithmeticException e)
{
throw new NullPointerException();
}
op: NullPointerException
-----------------------------------------------------------------------------------
--------------