[go: up one dir, main page]

0% found this document useful (0 votes)
11 views37 pages

Exception Handling

The document explains the differences between errors and exceptions in Java, detailing types of compilation and runtime errors, as well as predefined and user-defined exceptions. It outlines the importance of exception handling mechanisms to avoid abnormal terminations of applications and provides examples of common exceptions such as ArithmeticException and NullPointerException. Additionally, it discusses the 'throw' keyword for raising exceptions and the distinction between checked and unchecked exceptions.

Uploaded by

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

Exception Handling

The document explains the differences between errors and exceptions in Java, detailing types of compilation and runtime errors, as well as predefined and user-defined exceptions. It outlines the importance of exception handling mechanisms to avoid abnormal terminations of applications and provides examples of common exceptions such as ArithmeticException and NullPointerException. Additionally, it discusses the 'throw' keyword for raising exceptions and the distinction between checked and unchecked exceptions.

Uploaded by

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

Exception Handling:

—--------------------
Q)What is the difference between Error and Exception?
—-----------------------------------------------------
Ans:
—----
Error is a problem in the program, it will not allow the program to
execute.

There are two types of Errors.


1. Compilation Errors
2. Runtime Errors

Compilation Error:
It is a problem in java applications identified at compilation time
by the compiler.

There are three types of compilation errors.


a. Lexical Errors: Mistakes in the tokens.
EX: int a = 10; —----> Valid
nit a = 10; —----> Invalid, Lexical Error
b. Syntax Errors: Mistakes in the syntaxes.
EX: int a = 10; —----> Valid
a = 10 int; —----> Invalid, Syntax Error

c. Semantic Errors: Meaningless statements.


EX: Performing operations with the incompatible operands.
EX: int a = 10;
int b = 20;
int c = a + b; —> Valid.
EX: int a = 10;
char c = ‘A’;
boolean b = a + c; —---> Invalid, Semantic Error

Runtime Errors:
These are the problems identified at runtime by the JVM which are not
having solutions programmatically.

EX: Insufficient Main Memory Error.


EX: Unavailability of the IO components.
EX: Internal problem in JVM.
—--
—--
Exception:
These are the problems identified at runtime by the JVM which are
having solutions programmatically.

EX: FileNotFoundException
EX: NullPointerException
EX: IndexOutOfBoundsException
—---
—---
—---------------------------------------------------------------------
------
Exception:
—---------
Exception is an unexpected event occurred at runtime in Java
applications, which may be provided by the users while providing
dynamic input to the java applications, which may be provided by the
Database Engine while executing the sql queries in the JDBC
applications, which may be provided by the network when we establish
the connection between local machine[Client] and remote
machine[Server] in the distributed applications,...... causes abnormal
termination to the applications.

There are two types of terminations to the java applications.


1. Smooth Termination
2. Abnormal Termination

Smooth Termination: Terminating program execution at the end of the


program is called Smooth Termination.

Abnormal Termination: Terminating program execution in the middle of


the program is called Abnormal Termination.

In java applications, abnormal terminations of the programs may cause


the following serious problems.

1. The local Operating system may have crashed out.


2. The Database may be collapsed if it is the database related
application.
3. The network may be hung out if it is the network based
application.
4. The Server may be down if it is the server side applications
—-----
—-----
To avoid the above serious problems we have to avoid the abnormal
terminations to the program , here to avoid the abnormal terminations
to the programs we have to handle the exceptions properly, here to
handle the exceptions properly we have to use a set of mechanisms
explicitly called Exception Handling Mechanisms.

In general, in Java applications, Exceptions are always providing


abnormal terminations to the programs but Exception Handling
mechanisms always provide smooth termination to the applications.

Java is a Robust programming language, , because


1. Java has a very good memory management system in the form of Heap
memory management system , it is a dynamic memory management
system, it allocates and deallocates memory for the objects at
runtime of the application.
2. Java has very good exception handling mechanisms , because Java
has provided a very good predefined library and specialized
syntaxes to represent and to handle almost all the exceptions
which are coming frequently in the Java applications.

There are two types of Exceptions in Java.


1. Predefined exceptions
2. User defined exceptions

Predefined exceptions
—--------------------
These exceptions are defined by the Java programming language and
provided along with the java predefined library.
There are two types of predefined Exceptions.
1. Checked Exceptions
2. Unchecked Exceptions

Q)What is the difference between Checked Exceptions and Unchecked


Exceptions?
—---------------------------------------------------------------------
-------
Ans:
—---
1. Checked Exception is an exception recognized at compilation time by
the compiler[but not occurred at compilation, it will occur at runtime
only].

Unchecked Exception is an exception recognized at runtime by the JVM.

Note: In Java , whether the exception is checked exception or


unchecked exception , always exceptions will be generated at runtime
only, but some exceptions are recognized and notified at the
compilation that exceptions are called checked exceptions and some
other exceptions are not recognized at compilation and they are
recognized at runtime that exceptions are called Unchecked exceptions.

2. All the exception classes Except RuntimeException and its


subclasses, Error and its subclasses are the examples for the Checked
exceptions.

RuntimeException and its subclasses, Error and its subclasses are the
examples for the Unchecked Exceptions.
There are two types of Checked Exceptions.
1. Pure Checked Exceptions
2. Partially Checked Exceptions

Q)What is the difference between Pure Checked Exception and Partially


Checked Exceptions?
—---------------------------------------------------------------------
-------
Ans:
—----
If any Checked Exception has only checked exceptions as subclasses
then that checked exception is called Pure Checked Exception.
EX: IOException

If any Checked Exception has at least one subclass as an unchecked


exception then that checked exception is called a Partially Checked
Exception.
EX: Exception, Throwable
Overview of the predefined Exceptions:
—-------------------------------------
1. java.lang.ArithmeticException:
In Java applications, when a number is divided by zero then JVM will
raise java.lang.ArithmeticException.

EX:
package com.durgasoft.test;
public class Test {
public static void main(String[] args) {
int i = 100;
int j = 0;
float f = i / j;
System.out.println(f);

}
}

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


at com.durgasoft.test.Test.main(Test.java:9)

The above Exception message was divided into the following three
parts.

1. Exception Name : java.lang.ArithmeticException


2. Exception Description : / by zero
3. Exception Location : Test.java: 9

2. java.lang.NullPointerException:
In Java applications, when we access an instance variable or an
instance method by using a reference variable that contains null value
then JVM will raise java.lang.NullPointerException.
EX:
package com.durgasoft.test;
import java.util.Date;
public class Test {
public static void main(String[] args) {
Date date = null;
System.out.println(date.toString());

}
}
Exception Name : java.lang.NullPointerException
Exception Description : Cannot invoke "java.util.Date.toString()" because
"date" is null
Exception Location: Test.java: 10
3. java.lang.ArrayIndexOutOfBoundsException:
In Java applications, when we are trying to read an element from an
array at a particular index value and inserting an element at a
particular index value , where if the index value is not in the range
of the array indexes then JVM will raise an exception like
java.lang.ArrayIndexOutOfBoundsException.

EX:
package com.durgasoft.test;
public class Test {
public static void main(String[] args) {

int[] items = {10, 20, 30, 40};


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

}
}

Exception Name : java.lang.ArrayIndexOutOfBoundsException


Exception Description : Index 10 out of bounds for length 4
Exception Location : Test.java: 10

4. java.lang.StringIndexOutOfBoundsException:
In Java applications, if we perform any operation over the String data
on the basis of an index value which is not in the range of the String
indexes then JVM will raise an exception like
java.lang.StringIndexOutOfBoundsException.
EX:
package com.durgasoft.test;
public class Test {
public static void main(String[] args) {

String data = "Durgasoft";


System.out.println(data);
System.out.println(data.charAt(5));
System.out.println(data.charAt(15));
}
}

Exception Name: java.lang.StringIndexOutOfBoundsException


Exception Description : String index out of range: 15
Exception Location : Test.java: 10

5. java.lang.ClassNotFoundException:
In Java applications, to load a particular class bytecode to the
memory we have to use the following method from java.lang.Class
public static Class forName(String className)
EX: Class cls = Class.forName(“Employee”);

When we execute the above instruction, JVM will search for the
Employee.class at current location , at Java predefined library and at
the locations referred to the classpath environment variables. If the
Employee.class does not exist at all the above locations then JVM will
raise an exception like java.lang.ClassNotFoundException.

EX:
package com.durgasoft.test;
class Student{
}
public class Test {
public static void main(String[] args) throws Exception{
Class.forName("com.durgasoft.test.Employee");
}
}

Exception Name : java.lang.ClassNotFoundException


Exception Description : com.durgasoft.test.Employee
Exception Location: Test.java: 7
6. java.lang.InstantiationException:
In Java applications, if we load a class bytecode to the memory by
using Class.forName() method and if we want to create an object for
the loaded class then we have to use the following method from
java.lang.Class.

public Object newInstance() throws InstantiationException,


IllegalAccessException

EX: Class cls = Class.forName(“Employee”);


Object obj = cls.newInstance();

When JVM executes cls.newInstance() method JVM will search for the 0-
arg constructor in the loaded class, if the required 0-arg constructor
does not exist in the loaded class then JVM will raise an exception
like java.lang.InstantiationException

EX:
package com.durgasoft.test;
class Student{
public Student(String sname) {
}
}
public class Test {
public static void main(String[] args) throws Exception{
Class cls =
Class.forName("com.durgasoft.test.Student");
Object obj = cls.newInstance();
}
}

Exception Name: java.lang.InstantiationException


Exception Description : com.durgasoft.test.Student
Exception Location : Test.java: 10

7. java.lang.IllegalAccessException:
In Java applications, if we load a class bytecode to the memory by
using Class.forName() method and if we want to create an object for
the loaded class then we have to use the following method from
java.lang.Class.
public Object newInstance() throws InstantiationException,
IllegalAccessException

EX: Class cls = Class.forName(“Employee”);


Object obj = cls.newInstance();

When JVM executes cls.newInstance() method JVM will search for the non
private constructor in the loaded class, if the required non private
constructor does not exist in the loaded class then JVM will raise an
exception like java.lang.IllegalAccessException

EX:
package com.durgasoft.test;
class Student{
private Student() {
}
}
public class Test {
public static void main(String[] args) throws Exception{
Class cls = Class.forName("com.durgasoft.test.Student");
Object obj = cls.newInstance();
}
}

Exception Name: java.lang.IllegalAccessException


Exception Description : class com.durgasoft.test.Test cannot access a
member of class com.durgasoft.test.Student with modifiers "private"
Exception Location: Test.java: 10
8. java.lang.IllegalArgumentException:
In general, in Java applications, we may provide input data to the
methods by passing parameter values, in some methods there are
restrictions over the parameter values, if we provide any parameter
value against to the parameter restrictions then JVM will raise an
exception like java.lang.IllegalArgumentException.

EX: In Java applications, There is a fixed range for the priority


values to the Thread that is 1 to 10, in Java applications, to set a
particular priority value to the thread we have to use the following
method.

public void setPriority(int priorityValue)


Where the priorityValue must be in the range from 1 to 10, if we
provide any other value except in the range from 1 to 10 then JVM will
raise an exception like java.lang.IllegalArgumentException
EX:
package com.durgasoft.test;
public class Test {
public static void main(String[] args){
Thread t = new Thread();
System.out.println(t.getPriority());
t.setPriority(8);
System.out.println(t.getPriority());
t.setPriority(15);
}
}

Exception Name : java.lang.IllegalArgumentException


Exception Description : No description
Exception Location: Test.java: 10

9. java.lang.ClassCastException:
In Java applications, it is possible to keep subclass object reference
value in the superclass reference variable, but it is not possible to
keep superclass object reference value in the subclass reference
value, if we keep superclass object reference value in the subclass
reference variable then JVM will raise an exception like
java.lang.ClassCastException

EX:
package com.durgasoft.test;
class A{

}
class B extends A{

}
public class Test {
public static void main(String[] args){
B b =(B) new A();
}
}

Exception Name : java.lang.ClassCastException


Exception Description : class com.durgasoft.test.A cannot be cast to class
com.durgasoft.test.B (com.durgasoft.test.A and com.durgasoft.test.B are in
unnamed module of loader 'app')
Exception Location : Test.java: 10

10. java.io.FileNotFoundException:
In Java applications, if we want to read data from a particular source
file then we use java.io.FileInputStream.

EX
FileInputStream fis = new FileInputStream(“abc.txt”);

When we execute the above instruction, JVM will search for the abc.txt
file, if it is not available then JVM will raise an exception like
java.io.FileNotFoundException.

EX:
package com.durgasoft.test;
import java.io.FileInputStream;
public class Test {
public static void main(String[] args)throws Exception{
FileInputStream fis = new
FileInputStream("E:/abc/xyz/emp.txt");
}
}

Exception Name: java.io.FileNotFoundException


Exception Description : E:\abc\xyz\emp.txt (The system cannot find
the file specified)
Exception Location : Test.java: 7

throw keyword:
—-------------
The main purpose of the ‘throw’ keyword is to raise an exception in
the java application as per the application requirement.

Syntax:
throw new ExceptionName([ParamValue]);

EX:
package com.durgasoft.test;
class Student{

String sid;
String sname;
String saddr;
int smarks;

public Student(String sid, String sname, String saddr, int


smarks) {
this.sid = sid;
this.sname = sname;
this.saddr = saddr;
this.smarks = smarks;
}

public void getStudentStatus() {


String status = "";
System.out.println("Student Details");
System.out.println("---------------------");
System.out.println("Student Id : "+sid);
System.out.println("Student Name : "+sname);
System.out.println("Student Address : "+saddr);
System.out.println("Student Marks : "+smarks);
System.out.print("Student Status : ");
if(smarks >= 0 && smarks <= 100) {
if(smarks < 35) {
status = "FAIL";
}else if(smarks < 50) {
status = "THIRD CLASS";
}else if(smarks < 60) {
status = "SECOND CLASS";
}else if(smarks < 70) {
status = "FIRST CLASS";
}else {
status = "DISTINCTION";
}
}else {
throw new RuntimeException("Student Marks are
Invalid, Please provide the student marks in between 0 and
100");
}
System.out.println(status);
}
}
public class Test {
public static void main(String[] args)throws Exception{
Student std1 = new Student("S-111", "Durga", "Hyd",
89);
std1.getStudentStatus();
System.out.println();

Student std2 = new Student("S-222", "Anil", "Hyd",


150);
std2.getStudentStatus();
}
}

Student Details
---------------------
Student Id : S-111
Student Name : Durga
Student Address : Hyd
Student Marks : 89
Student Status : DISTINCTION
Student Details
---------------------
Student Id : S-222
Student Name : Anil
Student Address : Hyd
Student Marks : 150
Student Status : Exception in thread "main"
java.lang.RuntimeException: Student Marks are Invalid, Please
provide the student marks in between 0 and 100
at
com.durgasoft.test.Student.getStudentStatus(Test.java:38)
at com.durgasoft.test.Test.main(Test.java:50)

In Java applications, there are two ways to handle the exceptions.


1. By Using throws keyword.
2. By Using try-catch-finally.

‘throws’ keyword:
—-----------------
The main purpose of the throws keyword is to bypass the generated
exception from the present method to the caller method.

Syntax:
Void m1()throws Exception1,Exception2,Exception2,...Exception_n{
—-
}

In general, we will provide an exception class name along with the


throws keyword , it must be either the same as the generated exception
or superclass of the generated exception.

Note: In general, we will use the ‘throws’ keyword for the checked
exceptions.

EX:
import java.io.*;
class A{
void add()throws Exception{//here IOException will be converted
to Exception
concat();// IOException is available here, Line-4
}
void concat()throws IOException{// IOException is converted to
IOException
throw new IOException("My Own IOException");// Line-7
}
}
class Test{
public static void main(String[] args)throws Throwable{//
EXception will be converted to Throwable
A a = new A();
a.add();// Exception is available here, Line-13
}
}

D:\Fullstack10AM>javac Test.java

D:\Fullstack10AM>java Test
Exception in thread "main" java.io.IOException: My Own IOException
at A.concat(Test.java:7)
at A.add(Test.java:4)
at Test.main(Test.java:13)
When we compile the above program , the compiler will perform the
following actions.

1. Compiler will recognize the IOException in concat() method at


line-7.
2. Due to the throws keyword in concat() method declaration,
Compiler will convert the IOException to the IOException and
bypass the IOException to the caller of concat() method that is
at Line-4 in the add() method definition.
3. Due to the throws keyword in the add() method declaration, the
compiler will convert IOException to Exception and the compiler
will bypass Exception to the caller of add() method that is at
Line-13 in main() method.
4. Due to the throws keyword in the main() method declaration, the
compiler will convert the Exception to the Throwable and the
compiler will bypass Throwable to the JVM.

With the above steps, no compilation error is generated at the


compilation.

When we execute the above program, JVM will get IOException really
inside the concat() method and JVM will trace the Exception path with
the help of throws keyword and JVM will display the Exception message
along with its tracing locations.

Note: Identifying Exceptions, tracing the Exceptions path and


displaying the Exception details will be provided by an internal
component inside the JVM called “Default Exception Handler”.

Q)What are the differences between throw keyword and throws keyword?
—--------------------------------------------------------------------
Ans:
—---
1. ‘throw’ keyword can be used to generate or raise an exception in
java applications.

‘throws’ keyword can be used to bypass the generated exception


from the present method to the caller method to handle the
exception.
2. In general, ‘throw’ keyword will be used in the method body.

In general, ‘throws’ keyword will be used in the method


declaration.

3. ‘throw’ is able to allow only one Exception name.

‘throws’ keyword is able to allow more than one Exception name.

try-catch-finally:
—------------------
In Java applications, ‘throws’ keyword is not really an exception
handler, simply it bypasses the generated exception to the caller
method in order to handle that exception.

In Java applications, to handle the exceptions where the exceptions


are generated instead of bypassing exceptions we have to use try-
catch-finally.

Syntax:
try{
—----
—----
—----
}catch(ExceptionName refVar){
—-----
—----
—----
}finally{
—----
—----
—----
}

try block:
—----------
try block will take a set of instructions which may generate an
exception, where the set of instructions are called doubtful code.

In try-catch-finally, thye code which we provided inside the try block


may or may nor generate an exception.
If we have an exception in the try block then JVM will bypass flow of
execution to the catch block by skipping all the remaining
instructions inside the try block.

If we have an exceptional situation in the try block then JVM will


create an exception object internally and JVM will send the generated
exception object reference value to the catch block as the parameter.

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


the complete try block , at the end of the try block JVM will bypass
flow of execution to the finally block by skipping catch block
execution.

catch block:
—------------
The main purpose of the catch block is to catch the exception from the
try block and to display all the exception details on the console.

In Java applications, the catch block will be executed by the JVM when
we have an exception inside the try block .

There are three ways to provide exception details in the catch block.

1. By Using printStackTrace() method:


It will display the exception details like exception name,
exception description and exception location.
Note: It will be suggested when the project is in development
mode.

2. By Using System.out.println(exception):
It will display the exception details like exception name and
exception description but not exception location.

Initially, toString() method was defined in the java.lang.Object


class, it was implemented in such a way that to return a String
that contains ClassName@RefValue, later in all exception classes,
java.lang.Object class provided toString() method was overridden
in such a way that to return a string that contains Exception
details like “ExceptionName and Exception Description”.

If we pass an exception reference variable as parameter to


System.out.println() method then JVM will execute the Exception
class provided toString() method, it will return the exception
details like exception name and the exception description instead
of ClassName@RefValue.

Note: It will be suggested when the project is in Test mode

3. By Using getMessage() method:


It will display the exception details like exception description
but not exception name and exception location.

Note: It will be suggested when the project is in Production mode

EX:
package com.durgasoft.test;
public class Test {
public static void main(String[] args)throws Exception{
try {
float f = 100/0;
}catch (ArithmeticException e) {
e.printStackTrace();
System.out.println();

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

System.out.println(e.getMessage());
}finally {

}
}
}
java.lang.ArithmeticException: / by zero
at com.durgasoft.test.Test.main(Test.java:5)

java.lang.ArithmeticException: / by zero

/ by zero

Note: catch block will have an Exception class name, it must be either
the same as the generated exception in try block or superclass of the
generated exception in try block, it must not be the subclass of the
generated exception in the try block.

finally block:
—-------------
‘finally’ block will include a set of instructions which must be
executed by the JVM irrespective of getting an exception in try block
and irrespective of executing catch block.

In try-catch-finally,
1. try block is not giving guarantee to execute its instructions.
2. catch block is not giving guarantee to execute its instructions.
3. finally block is giving guarantee to execute its instructions.

In general, in java applications we will use some resources like


streams, database connections, network connections,.... As per the
application requirement.

In general, in java applications we will create and open all the above
specified resources at the starting point of the program, but we must
close them at the end of the program to avoid security problems
irrespective of performing the operations successfully.

In the above context, closing the resources is mandatory , so we must


provide all the closing related operations[Clean up operations] inside
the finally block.
Q)What is the difference between final, finalize and finally?
—-------------------------------------------------------------
Ans:
—---
‘final’ is a Java keyword, it can be used to declare constant
expressions.
In Java applications, the final keyword will be utilized in the
following three ways.
1. final variables: To fix its value throughout the program.
Not to change its value.
2. final method : To fix its implementation throughout the
program.
Not to override.
3. final class : To fix its implementation throughout the
program.
Not to have subclasses.

‘finalize()’ is a method in java defined in java.lang.Object class, it


will be used in Garbage COllection, it can be used to give a final
intimation about to destroy an object.This method will be executed by
the JVM automatically just before destroying object.

protected void finalize() throws java.lang.Throwable

‘finally’ is a block in try-catch-finally, it will include a set of


instructions which must be executed by the JVM irrespective of getting
an exception in try block and irrespective of executing catch block.

EX-1:
package com.durgasoft.test;
public class Test {
public static void main(String[] args){
System.out.println("Before try block");
try {
System.out.println("Inside try block, before Exception");
float f = 100/0;
System.out.println("Inside try block, after Exception ");
} catch (Exception e) {
System.out.println("Inside catch block");
}finally {
System.out.println("Inside finally block");
}
System.out.println("After finally block");
}
}

Before try block


Inside try block, before Exception
Inside catch block
Inside finally block
After finally block

EX-2:
package com.durgasoft.test;
public class Test {
public static void main(String[] args){
System.out.println("Before try block");
try {
System.out.println("Inside try block");
} catch (Exception e) {
System.out.println("Inside catch block");
}finally {
System.out.println("Inside finally block");
}
System.out.println("After finally block");
}
}

Before try block


Inside try block
Inside finally block
After finally block

EX-3:
package com.durgasoft.test;
class A{
int m1() {
try {
return 10;
} catch (Exception e) {
return 20;
}finally {
return 30;
}
}
}
public class Test {
public static void main(String[] args){
A a = new A();
System.out.println(a.m1());
}
}

30

EX:
package com.durgasoft.test;
class A{
int m1() {
try {
float f = 100/0;
return 10;
} catch (Exception e) {
return 20;
}finally {
return 30;
}
}
}
public class Test {
public static void main(String[] args){
A a = new A();
System.out.println(a.m1());
}
}

30

Q)Is it possible to write try block without having catch block?


—---------------------------------------------------------------
Ans:
—---
Yes, it is possible to write try block without having catch block, but
we must provide finally block.

try{
}finally{
}
EX:
package com.durgasoft.test;
public class Test {
public static void main(String[] args){
try {
System.out.println("Inside try");
}finally {
System.out.println("Inside finally");
}
}
}

Inside try
Inside finally

EX:
package com.durgasoft.test;
public class Test {
public static void main(String[] args){
try {
System.out.println("Inside try");
float f = 100/0;
}finally {
System.out.println("Inside finally");
}
}
}

Inside try
Inside finally
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.durgasoft.test.Test.main(Test.java:6)

Q)Is it possible to write try block without having finally block?


—-----------------------------------------------------------------
Ans:
—---
Yes, it is possible to write a try block without having a finally
block, but we must provide a catch block.

EX:
package com.durgasoft.test;
public class Test {
public static void main(String[] args){
try {
System.out.println("Inside try");
float f = 100/0;
}catch(Exception e) {
System.out.println("Inside catch");
}
}
}

Inside try
Inside catch

Note: In try-catch-finally syntax, along with try, we must provide


either catch block or finally block, it is not possible to write try
block only without having both catch block and finally, if we want to
write both catch and finally along with try block then we must provide
catch block first then finally block, it is not possible to
interchange the catch block and finally block.

try{
}catch(Exception e){
}finally{
}
Status: Valid

try{
}finally{
}catch(Exception e){
}
Status : Invalid

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


a. inside the try block?
b. Inside the catch block?
c. Inside the finally block?
—-----------------------------------------------------------------
Ans:
Yes, it is possible to provide try-catch-finally inside try, inside
catch, inside finally.

EX-1:
package com.durgasoft.test;
public class Test {
public static void main(String[] args){
System.out.println("Beofore outer try");
try {
System.out.println("Inside outer try, before nested try");
try {
System.out.println("Inside nested try");
}catch(Exception e) {
System.out.println("Inside Nested catch");
}finally {
System.out.println("Inside nested finally");
}
System.out.println("Inside outer try, after nested
finally");
}catch(Exception e) {
System.out.println("Inside Outer catch");
}finally{
System.out.println("Inside outer finally");
}
System.out.println("After Outer finally");
}
}

Beofore outer try


Inside outer try, before nested try
Inside nested try
Inside nested finally
Inside outer try, after nested finally
Inside outer finally
After Outer finally

EX:
package com.durgasoft.test;
public class Test {
public static void main(String[] args){
System.out.println("Beofore outer try");
try {
System.out.println("Inside outer try, before nested try");
try {
System.out.println("Inside nested try, before
exception");
float f = 100/0;
System.out.println("Inside nested try, after
exception");
}catch(Exception e) {
System.out.println("Inside Nested catch");
}finally {
System.out.println("Inside nested finally");
}
System.out.println("Inside outer try, after nested
finally");
}catch(Exception e) {
System.out.println("Inside Outer catch");
}finally{
System.out.println("Inside outer finally");
}
System.out.println("After Outer finally");
}
}
Beofore outer try
Inside outer try, before nested try
Inside nested try, before exception
Inside Nested catch
Inside nested finally
Inside outer try, after nested finally
Inside outer finally
After Outer finally

EX:
package com.durgasoft.test;
public class Test {
public static void main(String[] args){
System.out.println("Beofore outer try");
try {
System.out.println("Inside outer try, before Exception");
float f = 100/0;
System.out.println("Inside outer try, after Exception");
}catch(Exception e) {
System.out.println("Inside Outer catch, before nested
try");
try {
System.out.println("Inside nested try, before
exception");
float f = 100/0;
System.out.println("Inside nested try, after
exception");
}catch(Exception e1) {
System.out.println("Inside Nested catch");
}finally {
System.out.println("Inside nested finally");
}
System.out.println("Inside Outer catch, after nested
finally");
}finally{
System.out.println("Inside outer finally");
}
System.out.println("After Outer finally");
}
}

Beofore outer try


Inside outer try, before Exception
Inside Outer catch, before nested try
Inside nested try, before exception
Inside Nested catch
Inside nested finally
Inside Outer catch, after nested finally
Inside outer finally
After Outer finally

EX:
package com.durgasoft.test;
public class Test {
public static void main(String[] args){
System.out.println("Beofore outer try");
try {
System.out.println("Inside outer try, before Exception");
float f = 100/0;
System.out.println("Inside outer try, after Exception");
}catch(Exception e) {
System.out.println("Inside Outer catch");

}finally{
System.out.println("Inside outer finally, before nested
try");
try {
System.out.println("Inside nested try, before
exception");
float f = 100/0;
System.out.println("Inside nested try, after
exception");
}catch(Exception e1) {
System.out.println("Inside Nested catch");
}finally {
System.out.println("Inside nested finally");
}
System.out.println("Inside Outer finally, after nested
finally");
}
System.out.println("After Outer finally");
}
}

Beofore outer try


Inside outer try, before Exception
Inside Outer catch
Inside outer finally, before nested try
Inside nested try, before exception
Inside Nested catch
Inside nested finally
Inside Outer finally, after nested finally
After Outer 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 we must have the following conditions.

1. In the multiple catch blocks we are able to provide Exception


classes names , if all the exception classes are having
inheritance relation then we must provide all the catch blocks as
per the Exception classes inheritance increasing order, if we
violate this rule then the compiler will raise an error. If no
inheritance relation exists between exception classes then it is
possible to provide all catch blocks in any order.
2. If any catch has the pure checked exception then the respective
try block must raise the same pure checked exception, if it
violates this rule then the compiler will raise an error, if any
catch block has the non pure checked exception then the
respective try block may or may not raise the same exception.

EX:
try{
}catch(ArithmeticException e){
}catch(NullPointerException e){
}catch(ArrayIndexOutOfBoundsException e){
}
Status: Valid
EX:
try{
}catch(ArrayIndexOutOfBoundsException e){
}catch(ArithmeticException e){
}catch(NullPointerException e){
}
Status: Valid

EX:
try{
}catch(ArithmeticException e){
}catch(Exception e){
}catch(Throwable e){
}
Status: Valid

EX:
try{
}catch(Throwable e){
}catch(Exception e){
}catch(ArithmeticException e){
}
Status: Invalid

EX:
try{
throw new ArithmeticException();
}catch(ArithmeticException e){
}catch(NullPointerException e){
}catch(ArrayIndexOutOfBoundsException e){
}
Status: Valid

EX:
try{
throw new NullPointerException();
}catch(ArithmeticException e){
}catch(NullPointerException e){
}catch(ArrayIndexOutOfBoundsException e){
}
Status: Valid
EX:
try{
throw new ArithmeticException();
}catch(ArithmeticException e){
}catch(NullPointerException e){
}catch(ArrayIndexOutOfBoundsException e){
}catch(IOException e){//Pure checked exception
}
Status: Invalid
EX:
try{
throw new IOException();
}catch(ArithmeticException e){
}catch(NullPointerException e){
}catch(ArrayIndedxOutOfBoundsException e){
}catch(IOException e){//Pure checked exception
}
Status: Valid
User defined Exceptions:
—------------------------
These exceptions are defined by the developers as per the application
requirements.

In Java applications, if we want to provide user defined exceptions we


have to use the following steps.

1. Prepare User defined Exception class.


2. Raise the User defined exception and handle the user defined
exception.

Prepare User defined Exception class:


—-------------------------------------
1. Declare an user defined class.
2. Extend java.lang.Exception class to the user defined class.
3. Define a String parameterized constructor in the User defined
exception class, where the String parameter represents user
defined exception description.
4. In the String parameterized constructor access superclass string
parameterized constructor by using super() statement and by
passing the exception description as parameter.

EX:
public class InsufficientFundsException extends Exception{
public InsufficientFundsException(String exceptionDescription){
super(exceptionDescription);
}
}
Raise the User defined exception and handle the user defined
exception:
—---------------------------------------------------------------------
--
To raise an user-defined exception we have to use the “throw” keyword.
To handle user defined exceptions we have to use try-catch-finally.

try{
throw nw InsufficientFundsException(“Funds are not sufficient in
the Account”);
}catch(InsufficientFundsException e){
e.printStackTrace();
}

EX:
InsufficientFundsException.java
package com.durgasoft.exceptions;

public class InsufficientFundsException extends Exception{


public InsufficientFundsException(String message) {
super(message);
}
}

Account.java
package com.durgasoft.entities;

public class Account {


private String accountNumber;
private String accountHolderName;
private String accountType;
private long accountBalance;

public Account(String accountNumber, String accountHolderName,


String accountType, long accountBalance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.accountType = accountType;
this.accountBalance = accountBalance;
}

public String getAccountNumber() {


return accountNumber;
}

public void setAccountNumber(String accountNumber) {


this.accountNumber = accountNumber;
}

public String getAccountHolderName() {


return accountHolderName;
}

public void setAccountHolderName(String accountHolderName) {


this.accountHolderName = accountHolderName;
}

public String getAccountType() {


return accountType;
}

public void setAccountType(String accountType) {


this.accountType = accountType;
}

public long getAccountBalance() {


return accountBalance;
}
public void setAccountBalance(long accountBalance) {
this.accountBalance = accountBalance;
}
}

Transaction.java
package com.durgasoft.entities;

import com.durgasoft.exceptions.InsufficientFundsException;

public class Transaction {


private String transactionId;

public Transaction(String transactionId) {


this.transactionId = transactionId;
}

public void withdraw(Account account, int withdrawAmount){


try {
System.out.println("Transaction Details");
System.out.println("---------------------");
System.out.println("Transaction Id :
"+transactionId);
System.out.println("Account Number :
"+account.getAccountNumber());
System.out.println("Account Holder Name :
"+account.getAccountHolderName());
System.out.println("Account Type :
"+account.getAccountType());
System.out.println("Transaction Type :
WITHDRAW");
System.out.println("Withdraw Amount :
"+withdrawAmount);

if(withdrawAmount < account.getAccountBalance()){

account.setAccountBalance(account.getAccountBalance() -
withdrawAmount);
System.out.println("Account Balance :
"+account.getAccountBalance());
System.out.println("Transaction Status :
SUCCESS");
}else{
System.out.println("Account Balance :
"+account.getAccountBalance());
System.out.println("Transaction Status :
FAILURE");
throw new InsufficientFundsException("Reason:
Funds are not sufficient in your account");
}
}catch (InsufficientFundsException exception){
System.out.println(exception.getMessage());
}finally{
System.out.println("*************Thank You, Visit
again***********");
}
}
}

Main.java
import com.durgasoft.entities.Account;
import com.durgasoft.entities.Transaction;

public class Main {


public static void main(String[] args) {
Account account1 = new Account("abc123", "Durga",
"Savings", 25000);
Transaction transaction1 = new Transaction("t111");
transaction1.withdraw(account1, 10000);
System.out.println();

Account account2 = new Account("xyz123","Anil", "Savings",


10000);
Transaction transaction2 = new Transaction("t222");
transaction2.withdraw(account2, 25000);

}
}

Transaction Details
---------------------
Transaction Id : t111
Account Number : abc123
Account Holder Name : Durga
Account Type : Savings
Transaction Type : WITHDRAW
Withdraw Amount : 10000
Account Balance : 15000
Transaction Status : SUCCESS
*************Thank You, Visit again***********

Transaction Details
---------------------
Transaction Id : t222
Account Number : xyz123
Account Holder Name : Anil
Account Type : Savings
Transaction Type : WITHDRAW
Withdraw Amount : 25000
Account Balance : 10000
Transaction Status : FAILURE
Reason: Funds are not sufficient in your account
*************Thank You, Visit again***********

Java 7 version Features in Exception Handling:


—----------------------------------------------
1. Multi catch block
2. try-with-resources

Multi Catch block:


—-----------------
Up to Java 6 version, a single catch block is able to have only one
exception name, but from JAVA 7 version onwards we can provide more
than one Exception name in a single catch block.

try{
—---
}catch(Exception1 | Exception2 | …..|Exception-n refVar){
—----
}

Where Exception1, Exception2,...Exception-n must not have inheritance


relation.

EX:
import java.util.Date;
public class Main {
public static void main(String[] args) {
try{
//float f = 100/0;
/* Date date = null;
System.out.println(date.toString());*/
int[] a = {10,20,30,40};
System.out.println(a[10]);
}catch (NullPointerException | ArithmeticException |
ArrayIndexOutOfBoundsException exception){
exception.printStackTrace();
}
}
}
try-with-resources
—------------------
In general, in enterprise applications we will use the resources like
Streams, Database connections, Network connections,...as per the
application requirements.

If we perform the operations with the resources in the enterprise


applications we may get exceptions, here to handle exceptions if we
use try-catch-finally then we have to use the following conventions.

1. Declare the resources before try block.


2. Create the resources inside the try block.
3. Close the resources inside the finally block.

EX:
BufferedReader br = null;
Connection con = null;
Socket s = null;

try{
br = new BufferedReader(new InputStreamReader(System.in));
con = DriverManager.getConnection(--,--,--);
s = new Socket(“localhost”,8888);

}catch(Exception e){
}finally{
try{
br.close();
con.close();
s.close();
}catch(Exception e){
—---
}
}

With the above convention, we are able to get the following problems.

1. Writing try-catch-finally inside try-catch-finally is a bit


confusion oriented code.
2. In the above convention, Developers must close the resources, it
may not be guaranteed.

To overcome these problems we have to use try-with-resources.


try(Resource-1;Resource-2;...Resource-n;){
}catch(Exception e){
}

EX:

try(
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Connection con = DriverManager.getConnection(--,--,--);
Socket s = new Socket(“localhost”,8888);
){

}catch(Exception e){
—--
}

When we execute the try-with-resources, JVM will close all the


resources when it is coming outside of the try block.

In the above try-with-resources, All the resources must implement


java.lang.AutoCloseable marker interface either directly or
indirectly.

You might also like