80% found this document useful (5 votes)
2K views57 pages

Exception Handling PDF

The document discusses different types of exceptions in Java including checked exceptions like IOException and partially checked exceptions like Exception. It provides examples of predefined exceptions like NullPointerException, ArrayIndexOutOfBoundsException, FileNotFoundException, and how they occur. The document also covers the differences between checked and unchecked exceptions, and pure and partially checked exceptions.

Uploaded by

Anuj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
80% found this document useful (5 votes)
2K views57 pages

Exception Handling PDF

The document discusses different types of exceptions in Java including checked exceptions like IOException and partially checked exceptions like Exception. It provides examples of predefined exceptions like NullPointerException, ArrayIndexOutOfBoundsException, FileNotFoundException, and how they occur. The document also covers the differences between checked and unchecked exceptions, and pure and partially checked exceptions.

Uploaded by

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

JAVA Means DURGASOFT

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
1
JAVA Means DURGASOFT

Exception Handling
What is the difference between Error and Exception?

Error Exception

1. Error is a problem at runtime, for Exception is a problem, for which, we


which we are unable to provide are able to provide solution
solutions programmatically. programmatically.

Ex: JVM internal Problem Ex: ArithmeticException


StackOverFlowError NullPointerException
InSufficientMainMemory ArrayIndexOutOfBoundsException

Definition of Exception:

Exception is an Unexpected event occurred at runtime provided by the users


while entering dynamic input to the Java program, provided by the database
while executing sql queries in JDBC applications or provided by the remote
machine while establish connection between local machine and remote
machine in distributed applications causes abnormal termination to the Java
programs.

In Java applications, exceptions may provide abnormal terminations to the


Java programs, these abnormal terminations may effect operating system,
network applications.....

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
2
JAVA Means DURGASOFT

To overcome the above problems, we have to provide smooth terminations


to the Java applications, for this, we have to handle the exceptions properly,
for this, we have to use "Exception Handling Mechanisms".

Note: Terminating Java program in the middle is called as Abnormal


Termination, terminating Java program at the end is called as
Smooth Termination.

Java is Robust programming language, because,

1.Java is having very good memory management system in the form of


Heap memory Management System, a dynamic memory management
system, which allocated and deallocated memory for the objects at runtime
as per the JVM requirement.

2.Java is having very good Exception handling mechanisms due to the


availability of very good predefined library to represent each and every
exceptional situation.

There are two types of exceptions in Java:

1.Predefined Exceptions

2.UserDefined Exceptions

1.Predefined Exceptions:

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
3
JAVA Means DURGASOFT

These Exceptions are defined by Java programming language along with


Java predefined library.

There are two types of predefined exceptions:

1. Checked Exceptions

2. Unchecked Exceptions

Q)What is the difference between checked Exception and Unchecked


Exception?

1.Checked Exception is an exception identified by the compiler at


compilation time[occurred at runtime, not at compilation time].

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
4
JAVA Means DURGASOFT

NOTE:while Java program compilations, compiler will recognize


same situations to get exceptions at runtime then that exceptions
are called as Checked Exceptions.

Unchecked exceptions are the exceptions recognized by the JVM at runtime,


not a compiler at compilation time.

2.Runtime Exceptions and its subclasses, error and its subclasses are treated
as Unchecked exceptions and the remaining exception classes are treated as
checked exception.

There are two types of checked exceptions:

a)pure checked exceptions

b)partially checked exceptions.

Q)What is the difference between pure checked and partially checked


exceptions?

If any checked exception is having only checked exceptions are child classes
then that checked exceptions are called as "pure checked exceptions".

Ex:IOException

If any checked exception is having atleast one unchecked exception as a


child class then that checked exception is called as "partially Unchecked
exception"

Ex:Exception,Throwable

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
5
JAVA Means DURGASOFT

Review of Predefined Exceptions:

1.Arithmetic Exception:

In Java applications,when we have a situation like number divided by


zero,("num/0") then JVM will rise an exception like "Arithmetic Exception".

class Test{

public static void main(String args[]){

int i=100;

int j=0;

float f=i/j;

System.out.println(f);

}}

If we execute the above code then JVM will provide the following Exception
message. Exception in thread "main" java.lang.ArithmeticException:/by zero
at Test.main(Test.java7)

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
6
JAVA Means DURGASOFT

The above exception message is divided into the following three parts:

1.Exception Name :java.lang.ArithmeticException

2.Exception Description: / by zero

3.Exception location : Test.java:7

2.NullPointerException:

In Java applications,when we access any variable or method on a reference


variable having 'null' value then JVM will rise an exception like
"NullPointerException".

import java.util.*;

class Test{

public static void main(String args[]){

Date d=null;

System.out.println(d.toString());

}}

If we execute the above code then JVM will provide the following exception
details.

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
7
JAVA Means DURGASOFT

Exception Name : java.lang.NullPointerException

Exception Description:No Description

Exception Location:Test.java:7

3.ArrayIndexOutofBoundsException:

In Java applications,when we access a value from an array whose index


value is greater then orsame as array size then JVM will rise
"ArrayIndexOutOfBoundsException".

Ex:

class Test{

public static void main(String args[]){

int[] a={1,2,3,4};

System.out.println(a[4]);

}}

If we execute the above code then JVM will provide the following exception
message:

Exception Name:java.lang.ArrayIndexOutOfBoundsException

Exception Description:4
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
8
JAVA Means DURGASOFT

Exception Location:Test.java:10

4.FileNotFoundException:

In Java applications,when we are preparing FileInputStream or FileReader


with a particularsource file,where if the specified source file is not existed
then JVM will rise "FileNotFoundException"

Ex:

import java.io.*;

class Test{

public static void main(String args[]) throws Exception{

//FileInputStream fis=new FileInputStream("abc.txt");

FileReader fr=new FileReader("abc.txt");

}}

If we execute the above code then JVM will provide the following exception
message:

Exception Name:java.io.FileNotFoundException

Exception Description:abc.txt(The System Cannot Find the file specified)

Exception Location:Test.java:7
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
9
JAVA Means DURGASOFT

5.ClassNotFoundException:

In Java applications,when we trying to load a particular class bytecode to the


memory by usingClass.forName(-) method,where if the specified class .class
file is not available at currentlocation,at java predefined library and at the
locations refered by "classpath"environment variable then JVM will rise
"ClassNotFoundException".

class Test{

public static void main(String args[]){

Class.forName("A");

}}

If we execute the above code JVM will provide the following exception
details:

Exception Name:java.lang.ClassNotFoundException

Exception Description:A

Exception Location:Test.java:5

6.InstantiationException:

In Java applications,when we are creating an object for the particular class


by using newInstance() method from "java.lang.Class",where JVM will
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
10
JAVA Means DURGASOFT

search and execute 0-argument constructor,if the respective class is not


having 0-argument constructor then JVM will rise "InstantiationException".

class A{

static{

System.out.println(“Class Loading”);

A(int i){

System.out.println("Object Creating");

}}

class Test{

public static void main(String args[]) throws Exception{

Class c=Class.forName("A");

Object obj=c.newInstance();

}}

If we execute the above code then JVM will provide the following
ExceptionDetails.

Exception Name :java.lang.InstantiationException

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
11
JAVA Means DURGASOFT

Exception Description:A

Exception Location:Test.java:7

7.IllegealAccessException:

In Java applications, when we are trying to create object for a particular


class by using "newInstance()" method where JVM will search and execute
"non-private" constructor, where if the respective class is having only
"private" constructor then JVM will rise "IllegalAccessException".

Ex:

class A{

private A(){

System.out.println("Object Creating");

}}

class Test{

public static void main(String args[])throws Exception{

Class c=Class.forName("A");

Object obj=c.newInstance();

}}

If we execute the above code then JVM will provide the following exception
details.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
12
JAVA Means DURGASOFT

Exception Name:java.lang.IllegalAccessException

Exception Description:Class Test can not access a member of class A with


modifiers "private".

Exception Location:Test.java:10

8.IllegalArgumentException:

In general,in Java applications,we may provide methods with


parameters,where method parameters will allow the values on the basis of
the parameter dataTypes ranges.In some situations, methods may have
restrictions about the parameter values irrespective of dataTypes provided
ranges.In this context,if we provide any value which is not in the range
defined by the methods then JVM will rise an exception like
"IllegalArgumentException".

In Java,Threads are having priority values range that is from 1 to 10.If we


pass any priority value which is not in between 1 and 10 as a parameter to
setPriority() method then JVM will rise an exception like
"IllegalArgumentException".

class Test{

public static void main(String args[]){

Thread t=new Thread();

t.setPriority(15);

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
13
JAVA Means DURGASOFT

}}

If we execute the above code then JVM will provide the following exception
details.

Exception Name:java.lang.IllegalArgumentException

Exception Description:No Description

Exception Location:Test.java:10

9.IllegalThreadStateException:

In MultiThreading,when Main Thread[JVM created Thread to execute main()


method]access start()method over any thread reference then JVM will create
an Thread and JVM will start thatthread to access run() method of the
respective thread class.

In MultiThreading,if any Thread terminated along with Main Thread


automatically then thatthread is called as "Daemon Thread".

To make Daemon threads,we have to access setDaemon(true) method


before starting that thread.

If we access setDaemon(true) method after starting the thread then JVM will
rise an exceptionlike "IllegalThreadStateException".

class MyThread extends Thread{

public void run(){

while(true){

System.out.println("User Thread");
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
14
JAVA Means DURGASOFT

}}}

class Test{

public static void main(String args[]){

MyThread mt=new MyThread();

mt.setDaemon(true);

mt.start();

for(int i=0;i<10;i++){

System.out.println("Main Thread");

}}

If we run the above programme then JVM will provide the following
exception details.

Exception Name:java.lang.IllegalThreadStateException

Exception Description:No Description

Exception Location:Test.java:17

10.ClassCastException:

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
15
JAVA Means DURGASOFT

In Java applications,it is possible to keep sub class object reference value in


super classreference variable but it is not possible to keep super class object
reference value insub class reference variable.

In Java applications,when we are trying to keep super class object reference


value in subclass reference variable in downcasting then JVM will rise an
exception like"java.lang.ClassCastException".

class A{

class B extends A{

class Test{

public static void main(String args[]){

A a=new A();

B b=(B)a;

}}

If we run the above code then JVM will provide the following exceptional
details:

Exception Name:java.lang.ClassCastException

Exception Description:A cannot be cast to B

Exception Location:Test.java:10

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
16
JAVA Means DURGASOFT

“throw” keyword:

throw is a JAVA keyword,it can be used to raise an exception intentionally as


per the application requirement.

Syntax:

throw new Exception_Name([Param_List]);

NOTE:In general,we will utilize "throw" keyword in custom


exceptions inorder to risean exception.

Ex:

import java.io*;

class Test{

public static void main(String[] args)throws Exception{

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

System.out.println("Account Number :");

String accNo=br.readLine();

System.out.println("Account Name :");


DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
17
JAVA Means DURGASOFT

String accName=br.readLine();

int p_num=Integer.parseInt(pin_number);

if(p_num > 1000 && p_num < 9999){

System.out.println("Account Details");

System.out.println("----------------");

System.out.println("Account Number :"+accNo);

System.out.println("Account Name :"+accName);

System.out.println("Pin Number :"+XXXXXX);

System.out.println("Valid Pin Number");

else{

throw new RuntimeException("Invalid PIN Number");

}}}

If any statement we have provided immediately after "throw" statement


then compiler willrise an error like "unreachable statement".

class Test{

public static void main(String args[]){

System.out.println("Before Exception");
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
18
JAVA Means DURGASOFT

throw new ArithmeticException("My Arithmetic Exception");

System.out.println("After Exception");

}}

In Java,there are two ways to handle the exceptions:

1.By using "throws" keyword

2.By using try-catch-finally

1.”throws” keyword:

It is a Java keyword,it can be used to bypass the generated exception from


the present method or constructor to the caller method (or) constructor.

In Java applications,”throws” keyword will be used in method


declarations,not in method body.

In Java applications,”throws” keyword will allows an exception class name,it


should be either same as the generated exception or super class to the
generated exception.It should not be subclass to the generated Exception.

“throws” keyword will allow more than one exception in method prototypes.

In Java applications,”throws” keyword will be utilized mainly for checked


exceptions.

Ex:void m1() throws RuntimeException{

Throw new ArithmeticException();


DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
19
JAVA Means DURGASOFT

Status:Valid

Ex:void m1() throws FileNotFoundException{

Throw new IOException();

Status:InValid

Ex:

Void m1() throws NullPointerException,ClassNotFoundException{

Status:Valid

Ex:

Void m1() throws IOException,FileNotFoundException

Status:Valid

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
20
JAVA Means DURGASOFT

If we specify any super exception class along with throws keyword,then it is


not necessary to specify any of its child exception classes along with
“throws” keyword.

NOTE:In any Java method,if we call some other method which is bypassing
an exception by using “throws” keyword,then we must handle that exception
either by using “throws” keyword in the present method prototype or by
using “try-catch-finally” in the body of the present method.

Ex:

Void m1() throws Exception{

-----

------

Void m2(){

try{

m1();

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
21
JAVA Means DURGASOFT

catch(Exception e){

e.printStackTrace();

}}

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
22
JAVA Means DURGASOFT

void m1() throws Exception{

----

void m3() throws Exception{

m1();

Example program for “throws” keyword:

Import java.io.*;

class A{

void add() throws Exception{

concat();

Void concat() throws IOException{

throw new IOException();

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
23
JAVA Means DURGASOFT

class Test{

public static void main(String args[]) throws Throwable{

A a=new A();

a.add();

}}

Internal Flow:

If we compile the above program,then compiler will recognize throw keyword


in concat() method at Lline:10

With this compiler will generate exception notification with 6 line as


exception location,due to “throws” keyword in concat() method prototype
the specified exception will be bypasses to concat() method call in add()
method body at line:6,due to “throws” keyword in add(-) method
prototype,the specified exception is bypass to add() method call in main()
method that is at line:18,due to “throws” keyword in main() method
prototype,the specified exception will be bypassed to main() method call
that is to JVM.In this context,compiler will not provide any exception
notification,but when we execute the above program,Default Exception as
part of JVM will take that exception and it will provide the exception details
by including all the locations like 10th line,6th line and 18th line.

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
24
JAVA Means DURGASOFT

Q)What are the differences between “throw” and “throws” keywords?

Ans:

1.”throw” keyword can be used to “throws” keyword will by pass the


rise the exceptions intentionally as exceptions from the present method
Per the application reqirement. to the caller method.
2.”throw” keyword will be utilized in “throws” keyword will be used in
method body. method declarations or in method
prototype (or) in method header
part.
3.”throw” keyword will allow only one “throws” keyword will allow more
exception class name. than one exception class name.

try-catch-finally:

In Java application “throws” keyword is not really an exception


handler,because “throws” keyword will bypass the exception handling
responsibility from present method to the caller method.

If we want to handle the exceptions,the location where exceptions are


generated then we have to use “try-catch-finally”.

Syntax:

try{

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
25
JAVA Means DURGASOFT

catch(Exception_Name e){

finally{

where the purpose of try block is to include some java code where the
chances of getting exceptions.

If JVM identify any exception inside "try" block then JVM will bypass flow of
executionto "catch" block by skipping all the remaining instructions in try
block and by passingthe generated Exception object reference as parameter.

If no exception is identified in "try" block then JVM will execute completely


"try" block,at the end of try block JVM will bypass flow of execution to
"finally" block directly.

The main purpose of catch block is to catch the exception from try block and
to displayexception details on command prompt.

To display exception details on command prompt,we have to use the


following threeapproaches.

1.e.printStackTrace()

2.System.out.println(e):
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
26
JAVA Means DURGASOFT

3.System.out.println(e.getMessage());

1.e.printStackTrace():

It will display the exception details like Exception Name,Exception


Description andException Location.

2.System.out.println(e):

If we pass Exception object reference variable as parameter to


System.out.println(-)method then JVM will access Exception class toString()
method internally,it will displaythe exception details like Exception
name,Exception description.

3.System.out.println(e.getMessage()):

Where getMessage() method will return a String contains the exception


details like onlyDescription of the exception.

class Test{

public static void main(String args[]){

try{

throw new ArithmeticException("My Arithmetic Exception");

catch(ArithmeticException e){

e.printStackTrace();

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
27
JAVA Means DURGASOFT

System.out.println();

System.out.println(e);

System.out.println();

System.out.println(e.getMessage());

finally{

}}

Output:

java.lang.ArithmeticException:My Arithmetic Exception

at Test.main(Test.java:7)

java.lang.ArithmeticException:My Arithmetic Exception

My Arithmetic Exception

The main purpose of finally block is to include some Java code inorder to
executeirrespective of getting exception in "try" block and irrespective of
executing "catch"block.

Q)What is the difference between "final","finally" and "finalize" in JAVA?

1."final" is a keyword it can be used to declare constant expressions.

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
28
JAVA Means DURGASOFT

a)final variable:It will not allow modifications over its value.

b)final methods:It will not allow method overriding.

c)final class:It will not be extended.

2.finally block:It is a part in try-catch-finally syntax,it will include some


instructions,which must be executed by JVM irrespective of getting exception
from try block and irrespective of executing catch block.

3.finalize():It is a method in java.lang.Object class,it will be executed before


destroyingobjects inorder to give final notification to the user about to
destroy objects.

Q)Find the output from the following programs.

class Test{

public static void main(String args[]){

System.out.println("Before Try");

try{

System.out.println("Inside Try");

catch(Exception e){

System.out.println("Inside Catch");

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
29
JAVA Means DURGASOFT

finally{

System.out.println("Inside Finally");

System.out.println("After Finally");

}}

Output:

Before try

Inside try

Inside finally

After finally

class Test{

public static void main(String args[]){

System.out.println("Before Try");

try{

System.out.println("Before Exception in try");

float f=100/0;

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
30
JAVA Means DURGASOFT

System.out.println("After Exception in try");

catch(Exception e){

System.out.println("Inside Catch");

finally{

System.out.println("Inside Finally");

System.out.println("After Finally");

}}

Output:

Before try

Before exception in try

Inside catch

Inside finally

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
31
JAVA Means DURGASOFT

After finally

class A{

int m1(){

try{

return 10;

catch(Exception e){

return 20;

finally{

return 30;

}}}

class Test{

public static void main(String args[]){

A a=new A();

int val=a.m1();

System.out.println(val);

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
32
JAVA Means DURGASOFT

}}

Output:

30

NOTE:finally block provided return statement is the finally return statement


for the method

Q)Is it possible to provide "try" block without "catch" block?

Ans:Yes,it is possible to provide try block with out catch block but by using
"finally"Block.

try{

finally{

class Test{

public static void main(String args[]){

System.out.println("Before try");

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
33
JAVA Means DURGASOFT

try{

System.out.println("Before Exception inside try");

int i=100;

int j-0;

float f=i/j;

System.out.println("After Exception inside try");

finally{

System.out.println("Inside finally");

System.out.println("After Finally");

}}

Status:No Compilation Error.

Output:

Before try

Before exception inside try

Inside finally

Exception in thread “main” java.lang.ArithmeticException:/by zero

at Test.main(Test.java:11)

Reason:When JVM encounter exception in try block,JVM will search for catch
block,if no catch block is identified,then JVM will terminate the program
abnormally after executing finally block.

Q)Is it possible to provide "try" block with out "finally" block?

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
34
JAVA Means DURGASOFT

Ans:Yes,it is possible "try" block with out using "finally" block but by
providing "catch"block.

Ex:

try{

-------

--------

catch(Exception e){

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

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

Q)Is it possible to provide try-catch-finally

a)inside try block,

b)inside catch block and

c)inside finally block

Ans:Yes,it is possible to provide try-catch-finally inside try block,inside catch


blockand inside finally block.

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
35
JAVA Means DURGASOFT

Syntax-1:

try{

try{

catch(Exception e){

finally{

catch(Exception e){

finally{

Syntax-2:

try{

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
36
JAVA Means DURGASOFT

catch(Exception e){

try{

catch(Exception e)

finally{

finally{

Syntax-3:

try{

catch(Exception e){

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
37
JAVA Means DURGASOFT

finally{

try{

catch(Exception e){

finally{

}}

Q)Is it possible to provide more than one catch block for a single try block?

Ans:Yes,it is possible to provide more than one catch block for a single try
block but withthe following conditions.

1.If no inheritance relation existed between exception class names which are
specified alongwith catch blocks then it is possible to provide all the catch
blocks in any order.Ifinheritance relation is existed between exception class
names then we have to arrange allthe catch blocks as per Exception classes
inheritance increasing order.

2.In general,specifying an exception class along with a catch block is not


giving any guarantee to rise the same exception in the corresponding try
block,but if we specifyany pure checked exception along with any catch
block then the corresponding "try"block must rise the same pure checked
exception.
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
38
JAVA Means DURGASOFT

Ex1:

try{

catch(ArithmeticException e){

catch(ClassCastException e){

catch(NullPointerException e){

Status:Valid Combination

Reason:No Inheritance Relation is existed between exception classes.

Ex2:

try{

catch(NullPointerException e){

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
39
JAVA Means DURGASOFT

catch(ArithmeticException e){

catch(ClassCastException e){

status:Valid Combination

Ex3:

try{

catch(ArithmeticException e){

catch(RuntimeException e){

catch(Exception e){

Status:Valid

Reason:Inheritance Relationship

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
40
JAVA Means DURGASOFT

Ex4:

try{

catch(Exception e){

catch(RuntimeException e){

catch(ArithmeticException e){

status:Invalid

Ex5:

try{

throws new ArithmeticException("My Exception");

catch(ArithmeticException e){

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
41
JAVA Means DURGASOFT

catch(IOException e){

catch(NullPointerException e){

Status:Invalid

Ex6:

try{

throw new IOException("My Exception");

catch(ArithmeticException e){

catch(IOException e){

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
42
JAVA Means DURGASOFT

catch(NullPointerException e){

status:Valid

JAVA7 Features in Exception Handling:

1.Multi Catch block

2.Try-with-Resources/Automatic Resources Management/Auto close able


Resources

1.Multi Catch block:

Consider the below syntax:

try{

catch(Exception e){

If we specify "Exception" class along with catch block then it able to catch
and handleall the exceptions which are either same as Exception or child
classes to Exception,this approach will not provide specific handling for the

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
43
JAVA Means DURGASOFT

specific exceptions,it willhandle all the exceptions in the common way like
Exception object.

If we want to handle to the Exceptions separately then we have to use


multiple catch blocksfor a single try block.

try{

}catch(ArithmeticException e){

}catch(NullPointerException e){

}catch(ClassCastException e){

If we use this approach then no.of catch blocks are increased.

In Java applications,if we want to handle all the exceptions separately and


by usinga single catch block then we have to use "JAVA7" provided multi-
catch block

Syntax:

try{

catch(Exception1 | Exception2 |....|Exception-n e){

where Exception1,Exception2....must not have inheritance relation otherwise


Compilationerror will be raised.

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
44
JAVA Means DURGASOFT

Example Programme on Multi catch block example program:

class Test{

public static void main(String args[]){

try{

/* int a=10;

int b=0;

float c=a/b;

*/

/*java.util.Date d=null;

System.out.println(d.toString());

*/

int[] a={1,2,3,4,5};

System.out.println(a[10]);

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
45
JAVA Means DURGASOFT

catch(ArithmeticException | NullPointerException |
ArrayIndexOutOfBoundsException e){

e.printStackTrace();

}}

Try-With-Resources/Auto Closeable Resources:

In general,in Java applications,we may use the resources like


Files,Streams,Database Connections....as per the application requirements.

If we want to manage the resources along with try-catch-finally in Java


applications thenwe have to use the following conventions.

1.Declare all the resources before "try" block.

2.Create the resources inside "try" block.

3.Close the resources inside finally block.

The main intention to declare the resources before "try" block is to make
availableresources variables to "catch" block and to "finally" block to use.

If we want to close the resources in "finally" block then we have to use


close() methods,which are throwing some exceptions like

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
46
JAVA Means DURGASOFT

IOException,SQLException depending on the resourceby using "throws"


keyword,to handle these exceptions we have to use "try-catch-finally"inside
"finally" block.

//Declare the resources

File f=null;

BufferedReader br=null;

Connection con=null;

try{

//create the resources

f=new File("abc.txt");

br=new BufferedReader(new InputStreamReader(System.in));

con=DriverManager.getConnection("jdbc:odbc:nag","system","durga");

-----

-----

catch(Exception e){

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
47
JAVA Means DURGASOFT

finally{

//close the resources

try{

f.close();

br.close();

con.close();

}catch(Exception e){

e.printStackTrace();

}}

To manage the resources in Java applications,if we use the above convention


then developershave to use close() methods explicitly,Developers have to
provide try-catch-finallyinside "finally" block,this convention will increase
no.of instructions in Java applications.

To overcome all the above problems,JAVA7 version has provided a new


Feature in the formof "Try-With-Resources" or "Auto Closeable Resources".

In the case of "Try-With-Resources",just we, have to declare and create the


resources alongwith "try"[not inside try block,not before try block] and no
need to close these resourcesinside the finally block,why because,JVM will
close all the resources automaticallywhen flow of execution is coming out
from "try" block.

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
48
JAVA Means DURGASOFT

In the case of "Try-With-Resources",it is not required to close the resources


explicitly,it is not required to use close() methods in finally block explicitly,so
that it is notrequired to use "finally" block in try-catch-finally syntax.

Synatx:

try(Resource1;Resource2;........Resource-n){

-------

------

catch(Exception e){

-----

-----

Where all the specified Resources classes or interfaces must implement or


extend "java.io.AutoCloseable" interface.

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
49
JAVA Means DURGASOFT

Where if we declare resources as AutoCloseable resources along with "try"


then the resourcesreference variables are converted as "final" variables.

Ex:

try(File f=new File("abc.txt");

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

Connection
con=DriverManager.getConnection("jdbc:odbc:nag","system","durga");)

-------

-------

catch(Exception e){

e.printStackTrace();}

NOTE:In Java,all the predefined Stream classes,File class,Connection


interface areextends/implemented "java.io.AutoCloseable" interface
predefinedly.

import java.io.*;

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
50
JAVA Means DURGASOFT

class Test{

public static void main(String args[]){

try(FileInputStream fis=new FileInputStream("ScannerEx.java")

FileOutputStream fos=new FileOutputStream("DynamicEx2.java");)

int size=fis.available();

byte[] b=new byte[size];

fis.read(b);

fos.write(b);

System.out.println("File Transfered From ScannerEx.java to


DynamicEx2.java");

catch(Exception e){

e.printStackTarce();

}}}

Custom Exceptions/User Defined Exceptions:

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
51
JAVA Means DURGASOFT

Custom Exceptions are the exceptions,which would be defined by the


developers as per theirapplication requirements.

If we want to define user defined exceptions then we have to use the


following steps:

1.Define User defined Exception class:

To declare user-defined Exception class,we have to take an user-defined


class,which mustbe extended from java.lang.Exception class.

Class MyException extends Exception

2.Declare a String parametrized constructor in User-Defined Exception class


and access String parametrized super class constructor by using "super"
keyword:

class MyException extends Exception{

MyException(String err_Msg){

super(err_Msg);
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
52
JAVA Means DURGASOFT

}}

3.Create and Rise exception in Java application as per the application


requirement:

try{

throw new MyException("My Custom Exception");

catch(MyException me){

me.printStackTrace();

class InsufficientFundsException extends Exception{

InsufficientFundsException(String err_Msg){

super(err_Msg);

}}

class Transaction{

String accNo;

String accName;
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
53
JAVA Means DURGASOFT

String accType;

int initial_Amt=10000;

Transaction(String accNo,String accName,String accType){

this.accNo=accNo;

this.accName=accName;

this.accType=accType;

public void withdraw(int wd_Amt){

try{

System.out.println("Transaction Details");

System.out.println("-------------------");

System.out.println("Transaction Id :T123");

System.out.println("Account Number :"+accNo);

System.out.println("Account Name :"+accName);

System.out.println("Account Type :"+accType);

System.out.println("Transaction Type : WITHDRAW");

System.out.println("Initial Amount :"+initial_Amt);

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
54
JAVA Means DURGASOFT

System.out.println("Withdrawl Amount :"+wd_Amt);

int total_Amt=0;

if(wd_Amt<initial_Amt)

total_Amt=initial_Amt-wd_Amt;

initial_Amt=total_Amt;

System.out.println("Total Amount :"+total_Amt);

System.out.println("Transaction Status : SUCCESS");

else{

total_Amt=initial_Amt;

System.out.println("Total Amount :"+total_Amt);

System.out.println("Transaction Status:FAILURE");

throw new InsufficientFundsException("Amount is not sufficient in your


Account");

catch(InsufficientFundsException e){

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
55
JAVA Means DURGASOFT

System.out.println(e.getMessage());

System.out.println("********ThankQ,Visit Again***********");

class Test{

public static void main(String args[]){

Transaction tx1=new Transaction("abc123","Durga","Savings");

tx1.withdraw(5000);

System.out.println();

Transaction tx2=new Transaction("xyz123","Anil","Savings");

tx2.withdraw(15000);

}}

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
56
JAVA Means DURGASOFT

DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page
57

You might also like