0% found this document useful (0 votes)
14 views19 pages

CH 6 Exception - Handling

The document provides a comprehensive overview of exception handling in Java, including definitions, types of exceptions (checked and unchecked), and the mechanisms for handling exceptions using try, catch, and finally blocks. It explains the difference between exceptions and errors, the exception hierarchy, and the use of throw and throws statements for managing exceptions. Additionally, it covers best practices for creating customized exceptions and emphasizes the importance of handling exceptions to ensure normal program termination.

Uploaded by

Bl Gocher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views19 pages

CH 6 Exception - Handling

The document provides a comprehensive overview of exception handling in Java, including definitions, types of exceptions (checked and unchecked), and the mechanisms for handling exceptions using try, catch, and finally blocks. It explains the difference between exceptions and errors, the exception hierarchy, and the use of throw and throws statements for managing exceptions. Additionally, it covers best practices for creating customized exceptions and emphasizes the importance of handling exceptions to ensure normal program termination.

Uploaded by

Bl Gocher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 19

*******[durga-volume 2 : 1-40]******************

**EXECEPTION:- is an unwanted unexpected event that distrubs normal flow of the


programm is called exception.
-------------
Ex: FileNotFoundExeception

Imp_note:=> it is highly recommended to handle exception


the main objective of handle exception is normal termination of
programm.

Q-what is meaning of exception handling ?


Ans: defining alternative way to continue rest of prog normally. its 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.

*** DEFAULT EXCEPTION HANDLING IN JAVA:


=======================================
> if exception raised inside any mehtod then that method is responsible to create
exception object with following information.

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 .

> this process continued until main() mehtod and


if main method also not contains handling code then JVM terminate main also and
remove from stack.
then
> JVM handovers responsibilty of exception handling to default exception
handler(its part of jvm).
then

"Default exception handler"-> prints exception info to console and terminates


programm abnormally.
** Exception Hierarchy:
-----------------------

Objcet
|
Throwable

Note:-Throwable acts as root for Exception Hierarchy


Throwable class contain two child classes - Exception , Error.

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.

*** CHECKED Vs UNCHECKED EXCEPTION:


-----------------------------------

CHECKED : - Exception which are checked by compiler for smooth execution of


programm at runtime are called checked Exception.
[whether programmer handling or not].
or
classes that extend Throwable class [except RuntimeException and Error]
are known as checked exceptions
e.g.
IOException,
SQLException etc,
ServletException,

Note:- Checked exceptions are checked at compile-time.


ex: FileNotFoundException

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

Note:- whether Exception is checked or uncheked compulsory it should occurs at


runtime only.
and there is no chance of occuring any Exception at compile time.

** FULLY CHECKED Vs PARTIIALLY CHECKED:


---------------------------------------
FULLY CHECKED:- if its all child classes are also checked.

ex: IOException
InterruptedException

PARTIIALLY CHECKED:- if some of its child classes are unchecked.

ex : Exception
the only PARTIIALLY CHECKED Exception in java are:
ex:
Throwable
Exception

Q Which is checked or unchecked or partialy checked?


ans:

1 RuntimeException => Unchecked


2 Error => unchecked
3 ArthimaeticException => unchecked
4 NullPointerException => unchecked

5 IOException => fully checked


6 InterruptedException => fully checked
7 FileNotFoundException => fully checked

8 Exception => partially checked


9 Throwable => partially checked

** CUSTOMIZED EXCEPTION HANDLING [BY USING- TRY , CATCH]:


---------------------------------------------------------
Risky Code:- code which may raise exception is called risky code.
we have to place risky code inside try block
and
its handling code inside catch block.

**CONTROL-FLOW IN TRY CATCH:


----------------------------

try
{
stmt 1;
stmt 2;
stmt 3;
}
catch(X e)
{
stmt 4;
}

stmt 5;

Note:-

CASE 1: if there is no exception.


1,2,3,4,5

CASE 2: if exception raised at stmt 2 and catch block matched then


1,4,5

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.

CASE 4: if exception raised at stmt 4 or stmt 5 then its always abnormal


termination of programm.

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.

** VARIOUS METHODS TO PRINT EXCEPTION INFORMATION:


--------------------------------------------------

Note:- Throwable class define following 3 methods to print exception info to


console

1 printStrackTrack(): 1 Name of exception


2 Description of exception
3 Stac trace

2 toString() : 1 Name of exception


2 Description of exception

3 getMessage(): 1 Description of exception

Imp_Note:-> Default exception handler internally uses printStackTrace() method to


print exception information to the console.

** TRY WITH MULTIPLE CATCH BLOCKS:


----------------------------------
try with multiple catch is possible and recommended to use.

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.

** DIFFERENCE BW FINAL, FINALLY, FINALIZE:


------------------------------------------

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.

*** VARIOUS POSSIBLE COMBINATION OF TRY CATCH FINALLY:


------------------------------------------------------
1 : whenever we are writing try block compulsory we should write either catch or
finally-
mean try without catch , or finally is invalid.

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.

4 : in try- catch - finally order is important.

5 : with in try catch finally, we can take nested try catch finally,

6 for try catch finally curly braces are mandatory.

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){
}

-------------------------------------------

*** THROW STATEMENT:


======================
> we can create Exception object explicitally and we can handover to JVM manually
by using throw kw.

ex: throw new ArthimeticException("\ by zero");


Note:- in above stmt, creating explicitally ArthimeticException object new.

Note:- Generally we can use throw kw for customized exceptions but not for
predefined exceptions.

CASE 1: throw e; // if e refer null then we get NPE.

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:

class test extends RuntimeException


{
PSVM()
{
throw new Test();
}
}

*** THROWS STATEMENT:


---------------------
1 :we can use Throws kw to delegate the responsibility of exception handling to
caller method. then caller method is responsible to handle that exception.

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.

NOTE:- recommmed to use try catch over throws kw.

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.

// if we are not handling


ex: PrintWriter pw = new PrintWriter("abc.txt");
pw.println("hello"); // unreported exception:-
FileNotFounException,must be caught/declared to be thrown

or

Thread.sleep(5000); // unreported exception:-


java.lang.InterptedException, must be caught/declared to be thrown

Note:- we can handle this CE by using 2 ways:


---------------------------------------------

1 : By using try catch:


-----------------------
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
//
}

op: compile and run successfully

2 : By using Throws kw:


---------------------------

Class Test
{
PSVM() throws InterruptedException
{
Thread.sleep(5000);
}
}

ex:2
-----

1 : By using try catch:

try
{
sop(10/0);
}
catch(ArthimeticExceptin e)
{
//
}

op: compile and run successfully

2 : By using Throws kw:


---------------------------

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.

*** EXECPTION HANDLING KW SUMMERY:


----------------------------------

1 TRY: - to maintain risky code.


2 CATCH:- to maintain handling code .
3 FINALLY:- to maintain clean up code.
4 THROW :- to hand over our created exception object to JVM manually.
5 THROWS :- to delegate responsiblity of excepiton handling to caller method.

** CUSTOMIZED EXCEPTIONS [USER DEFINED EXCEPTIONS]:


---------------------------------------------------

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:

public static void main(String[] args) {

Scanner s = new Scanner(System.in);


int age=s.nextInt();

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");
}
}

** Note:-it is highly recomonded to maintain our customized exceptions as unchecked


by extending RuntimeException.
we can catch any Throwable type including Errors also.

ex:
try{
}
catch(Error e)
{
} // valid

*** TOP 10 EXCEPTIONS:


======================
All exceptions are divided into 2 type

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

*** TOP 10 EXCEPTIONS:


----------------------

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:

Exception / Error Raised by


-----------------------------------------------------------------------------------
-----------
1 ArrayIndexOutOfBoundException: |
|
2 NullPointerException: |
|
3 StackOverFlowError |
| Raised automatically by JVM [jvm
exceptions]
4 NoClassDefFoundError |
|
5 ClassCastException |
|
6 ExceptionInInitializerError |
-----------------------------------------------------------------------------------
-----------
|
1 IllegalArgumentException |
|
2 NumberFormatException |
| Raised explicitally either by programmer
or
3 IllegalStateException | by API developer [Programatic
Exception]
|
4 AssetrtionError |
|
-----------------------------------------------------------------------------------
-----------

** 1.7 VERSION ENHANSEMENT:


---------------------------
following 2 concepts introduced

1 try with resources


2 multi catch blocks

1 try with resources:


---------------------
until 1.6 its highly recomended to write finally block to close all resources which
are open as part of try block.

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:

tryk (r1 , r2, r3)


{

2 All resources should be AutoClosable resources.


Note:- a resource said to be auto closable if the corresponding class impliments
java.lang.AutoClosableinterfacce either directally or indirectally.
Note:- all database related, network related and file IO related resources already
implimented AutoClosable interface.
we r not required to do anything.

3 All resources reference vars are implicitally final and we can not perform
reassignment with in try block.

Imp_Note:

4 until 1.6 try should be followed by either catch or finally


but
1.7 v we can take only try with resource without catch or finally.

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.

**2 multi catch block :


-----------------------
util 1.6 v , even though multiple exceptions having same handling code , but we
have to write a seperate catch block for every exception,

To overcome this "Multi catch block" concepts introduced.

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)

Q - what is Exception Propagation ?


------------------------------------
ans:- with in a method if an Exception raised and if that method do not handled
that Exception , then Exception object will be propagated to the caller method then
caller method is responsible to handle that Exception ,
this process is known as "Exception propagation".

Q- what is Rethrowing an Exception ?


------------------------------------
ans:- to convert the one exception type to another exception type, we use
rethrowing Exception concept.
ex:

try
{
sop(10/0);
}
catch(ArithmeticException e)
{
throw new NullPointerException();
}

op: NullPointerException

-----------------------------------------------------------------------------------
--------------

You might also like