Exception Handling
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.
Compilation Error:
It is a problem in java applications identified at compilation time
by the compiler.
Runtime Errors:
These are the problems identified at runtime by the JVM which are not
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.
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
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
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);
}
}
The above Exception message was divided into the following three
parts.
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) {
}
}
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) {
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");
}
}
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();
}
}
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
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();
}
}
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();
}
}
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");
}
}
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;
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)
‘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{
—-
}
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.
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.
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.
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.
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.
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.
2. By Using System.out.println(exception):
It will display the exception details like exception name and
exception description but not exception location.
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 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.
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");
}
}
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");
}
}
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
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)
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
try{
}catch(Exception e){
}finally{
}
Status: Valid
try{
}finally{
}catch(Exception e){
}
Status : Invalid
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");
}
}
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");
}
}
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");
}
}
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.
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;
Account.java
package com.durgasoft.entities;
Transaction.java
package com.durgasoft.entities;
import com.durgasoft.exceptions.InsufficientFundsException;
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;
}
}
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***********
try{
—---
}catch(Exception1 | Exception2 | …..|Exception-n refVar){
—----
}
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.
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.
EX:
try(
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Connection con = DriverManager.getConnection(--,--,--);
Socket s = new Socket(“localhost”,8888);
){
}catch(Exception e){
—--
}