Exception Handling
Exception Handling
Exception Handling
Types of Exceptions:-
As per sun micro systems standards The Exceptions are divided into three types
1) Checked Exception
2) Unchecked Exception
3) Error
checkedException:-
The Exceptions which are checked by the compiler at compilation time for the proper execution
of the program at runtime is called CheckedExceptions.
Ex:- IOException,SQLException etc……….
155 | P a g e
uncheckedException:-
The exceptions which are not checked by the compiler at compilation time is called
uncheckedException . These checking down at run time only.
Ex:- ArithmeticException,NullPointerException, etc……….
Error:-
Errors are caused by lack of system resources . these are non recoverable.
Ex:- StackOverFlowError,OutOfMemoryError,AssertionError etc…………
Goodpoint:-
The Exception whether it is checked or unchecked the Exceptions are occurred at runtime.
Exception:-
An exception is unwanted unexpected event these are caused by the programmer mistake.
Exceptions are recoverable.
Ex:- IOException,SQLExcetion,RuntimeExecption etc……………
156 | P a g e
Error:-
Errors are caused by lack of system resources . these are non recoverable.
Ex:- StackOverFlowError,AssertionError etc…………
Object
Throwable
Exception Error
ArithmeticException
NullPointerException
ArrayIndexOutOfBounds
ClassCastException
NumberFormat
etc
Note:-
1) RuntimeException and its child classes and Error and its child classes are Unchecked
remaining all are checkedExceptions.
2) Root class for all Exception hierarchy is Throweable class.
1) try
2) catch
3) finally
4) throw
5) throws
Exception Handling:-
157 | P a g e
It is recommended to handle the Exception the main of the Exception Handling is normal
Execution of the program or graceful termination of the program at runtime.
We are able to handle the exception in two ways.
1. By using try-catch blocks
2. By using throws keyword.
Syntax:-
try
{
Code to run [break;]
}
Catch(ExceptionName reference_variable)
{
Code to run if an exception is raised
}
Output:- durga
Software
Exception in Thread “main” :java.lang.ArithmeticException: / by zero
Note:- if we are not using try-catch it is always abnormal termination if an Exception raised.
158 | P a g e
1) If we are taking try-catch the program goes to normal termination. Because the risky code we
are taking inside the try block and handling code we are taking inside the catch block.
2) If the exception is raised in the try block the corresponding catch block is executed.
3) If the corresponding catch block is not there program goes to abnormal termination.
class Test
{
public static void main(String[] args)
{
System.out.println("durga");
System.out.println("software");
try
{
System.out.println(10/0);
}
catch (ArithmeticException e)
{
System.out.println("you are getting AE "+e);
}
System.out.println("solutions");
}
}
Output:- durga
Software
You are getting AE: java.lang.ArithmeticException: / by zero
Solutions.
Ex 1:-
Exception raised in try block the JVM will search for corresponding catch block if the catch block
is matched, corresponding catch block will be executed and rest of the code is executed normally.
class Test
{
public static void main(String[] args)
{
System.out.println("program starts");
try
{
int[] a={10,20,30};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println("we are getting exception");
159 | P a g e
}
System.out.println("rest of the code");
}
}
Ex 2:-
Exception raised in try block the JVM will search for corresponding catch block if the catch block
is matched, corresponding catch block will be executed and rest of the code is executed normally. If the
catch block is not matched the program is terminated abnormally.
class Test
{
public static void main(String[] args)
{
System.out.println("program starts");
try
{
int[] a={10,20,30};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
}
catch(ArithmeticException ae)
{
System.out.println("we are getting exception");
}
System.out.println("rest of the code");
}
}
Ex 3:- if there is no exception in try block the catch blocks won’t be executed.
Class Test
{
public static void main(String[] args)
{
System.out.println("program starts");
try
{
System.out.println("ratan sir");
System.out.println("how r u");
}
catch(ArithmeticException ae)
{
System.out.println("we are getting exception");
}
System.out.println("rest of the code");
}
}
160 | P a g e
Ex 4:- independent try blocks are not allowed in java language.(compilation error)
class Test
{
public static void main(String[] args)
{
System.out.println("program starts");
try
{
int a=10/0;
}
System.out.println("rest of the code is avilable");
}
}
Ex 5:-
In between try and catch independent statements are not allowed. If we are providing
independent statements the compiler will raise compilation error.
class Test
{
public static void main(String[] args)
{
System.out.println("program starts");
try
{
int a=10/0;
}
System.out.println(“in between try and catch”);
catch(ArithmeticException e)
{
int a=10/5;
System.out.println(a);
}
System.out.println("rest of the code is avilable");
}
}
161 | P a g e
Ex 6:-
1) Inside the try block once we are getting exception the JVM search for the corresponding catch
block .
2) If the catch block is matched then it will executed that catch block the program is terminated
normally the control never goes try block once again.
3) Once the control is out of the try block the control never entered into try block once again .
Ex 7:- The way of handling the exception is varied from exception to the exception so it is
recommended to provide try with number of catch blocks.
import java.util.*;
class Test
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("provide the division value");
int n=s.nextInt();
try
{
System.out.println(10/n);
String str=null;
System.out.println("u r name is :"+str);
System.out.println("u r name length is--->"+str.length());
}
catch (ArithmeticException ae)
162 | P a g e
{
System.out.println("good boy zero not allowed geting Exception"+ae);
}
catch (NullPointerException ne)
{
System.out.println("good girl getting Exception"+ne);
}
System.out.println("rest of the code");
}
}
Ex 8:- By using root class (Exception) we are able to hold any type of exceptions.
import java.util.*;
class Test
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("provide the division value");
int n=s.nextInt();
try
{
System.out.println(10/n);
String str=null;
System.out.println("u r name is :"+str);
System.out.println("u r name length is--->"+str.length());
}
catch (Exception e)
{
System.out.println("getting Exception"+e);
}
System.out.println("rest of the code");
}
}
Ex 9:-in java class if we are declaring multiple catch blocks at that situation the catch block order should
be child to parent shouldn’t be parent to the child.
163 | P a g e
(No compilation error) Compilation error
Child-parent import java.util.*;
import java.util.*; class Test
class Test {
{ public static void main(String[] args)
public static void main(String[] args) {
{ Scanner s=new Scanner(System.in);
Scanner s=new Scanner(System.in); System.out.println("provide the division val");
System.out.println("provide the division val"); int n=s.nextInt();
int n=s.nextInt(); try
try {
{ System.out.println(10/n);
System.out.println(10/n); String str=null;
String str=null; System.out.println("u r name is :"+str);
System.out.println("u r name is :"+str); System.out.println("u r name length is--
System.out.println("u r name length is-- ->"+str.length());
->"+str.length()); }
} catch (Exception ae)
catch (ArithmeticException ae) {
{
System.out.println("Exception"+ae); System.out.println("Exception"+ae);
} }
catch (Exception ne) catch (ArithmeticException ne)
{ {
System.out.println("Exception"+ne);
System.out.println("Exception"+ne); }
} System.out.println("rest of the code");
System.out.println("rest of the code"); }
}} }
164 | P a g e
Possibilities of try-catch blocks:- }
1)single time try-catch:- catch ()
try {
{ }
} 5)catch with try-catch:-
catch () try
{ {
} }
2)multiple times try-catch:- catch ()
try {
{ try
} {
catch ()
{ }
} catch ()
try {
{ }
} }
catch ()
{ 6)
} try
{
3)try with multiple catchs:- try
try {
{
} }
catch () catch ()
{ {
} }
catch () }
{ catch ()
} {
4)nested try-catch:- try
try {
{
try }
{ catch ()
} {
catch () }
{ }
}
165 | P a g e
1)single time try-catch:-
1) if we are provide try-catch whenever we are getting Exception the corresponding catch block is
matched then the code executed good then we are getting normal flow of execution.
2) If the corresponding catch block is not matched then our program always goes to abnormal
termination.
try
{
Risky code
}
catch ()
{
Alternative code
}
Ex 1 :-
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("hi girls");
System.out.println(10/0);
System.out.println("hi boys");
}
catch (ArithmeticException e)
{
System.out.println("we are getting ArithematicException"+e);
}
System.out.println("if we provide try-catch");
System.out.println("the rest of the code is executed");
}
};
166 | P a g e
2)multiple times try-catch:-
try
{
}
catch ()
{
}
try
{
}
catch ()
{
}
Ex:-
class Test
{
static String str;//instance variable default value is :null
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
System.out.println("we are getting ArithematicException"+ae);
}
try
{
System.out.println(str.length());
}
catch (NullPointerException ne)
{
System.out.println("we are getting nullpointerException"+ne);
}
System.out.println("if we provide try-catch");
System.out.println("the rest of the code is executed");
}
};
167 | P a g e
3)try with multiple catchs:-
try
{
}
catch ()
{
}
catch ()
{
}
Ex:-
import java.util.*;
class Test
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("provide the division value");
int n=s.nextInt();
try
{
System.out.println("********good boy check the output********");
System.out.println(10/n);
String str=null;
System.out.println("u r name is :"+str);
System.out.println("u r name length is--->"+str.length());
}
catch (ArithmeticException ae)
{
System.out.println("good boy zero not allowed geting Exception"+ae);
}
catch (NullPointerException ne)
{
System.out.println("good girl getting Exception"+ne);
}
System.out.println("rest of the code");
}
}
168 | P a g e
4)nested try-catch:-
try
{
try
{
}
catch ()
{
}
}
catch ()
{
}
Ex:-
class Test
{
public static void main(String[] args)
{
try
{
try
{
System.out.println("first try block");
int a=10/0;
System.out.println(a);
}
catch (ArithmeticException ae)
{
System.out.println("first catch block"+ae);
}
try
{
System.out.println("second try block");
int[] a={10,20,30};
System.out.println(a[5]);
}
catch (ArrayIndexOutOfBoundsException aaa)
{
System.out.println("second catch block"+aaa);
}
}
catch (Exception e)
{
System.out.println("main catch"+e);
}
System.out.println("normal flow of execution");
}
}
169 | P a g e
5)catch with try-catch:-
try
{
}
catch ()
{
try
{
}
catch ()
{
}
}
Ex:-
import java.util.*;
class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
try
{
System.out.println("hi Rattaiah");
}
catch (Exception e)
{
System.out.println(e);
}
}
}}
Ex :-
statement 1
statement 2
try
{
statement 3
try
{
statement 4
statement 5
}
catch ()
{
170 | P a g e
statement 6
statement 7
}
}
catch ()
{
statement 8
statement 9
try
{
statement 10
statement 11
}
catch ()
{
statement 12
statement 13
}
}
statement 14
statement 15
case 1:-
if there is no Exception in the above example
1, 2, 3, 4, 5, 14, 15 Normal Termination
Case 2:-
if the exception is raised in statement 2
1 , Abnrmal Termination
Case 3:-
if the exception is raised in the statement 3 the corresponding catch block is matched.
1,2,8,9,10,11,14,15 normal termination
Case 4:-
if the exception is raise in the statement-4 the corresponding catch block is not matched and
outer catch block is not matched.
1,2,3 abnormal termination.
Case 5:-
If the exception is raised in the statement 5 and corresponding catch block is not matched and
outer catch block is matched.
1,2,3,4,8,9,10,11,14,15 normal termination
Case 6:-
If the exception is raised in the statement 5 and the corresponding catch block is not matched
and outer catch block is matched while executing outer catch inside the try block the the
exception is raised in the statement 10 and the corresponding catch is matched.
1,2,3,4,8,9,12,13,14,15 normal termination.
Case 7:-
If the exception raised in statement 14.
1,2,3,4,5 abnormal termination.
171 | P a g e
Finally block:-
1) finally is a block it is always executed irrespective of try and catch.
2) Finally contains clean-up code.
3) It is not possible to write finally alone . we must take try-catch-finally otherwise take the try-
finally these two are the possibilities. If we are taking any other we are getting compilation error
saying finally without try block .
Syntax:-
try
{
risky code;
}
catch (Exception obj)
{
handling code;
}
finally
{
free code;
}
Ex :- Exception raised in try block and corresponding catch block is matched then rest of the code is
executed normally.
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("durga");
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
System.out.println("u r getting ae:"+ae);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code");
}
}
Output:- durga
U r getting ae:ArithmeticException : /by zero
Finally block is always executed
172 | P a g e
DurgaSoftware solutions Mr. Ratan
Ex:-
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("durga");
System.out.println(10/0);
}
catch (NullPointerException ne)
{
System.out.println("u r getting ne"+ne);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code"); //this line not executed
}
}
Output:- durga
Finally block is always executed
Exception in Thread “main” :java.lang.ArithmeticException: / by zero
Ex:- finally block is not executed vs finally block is executed
class Test
{
public static void main(String[] args)
{
System.out.println("ratan1");
System.out.println("ratan2");
int a=10/0;
try
{
System.out.println("ratan");
}
finally
{
System.out.println("finally block");
}
System.out.println("rest of the code");
}
};
The only one situation the finally block is wont be executed:-
In your program whenever we are using System.exit(0) the JVM is shut downing hence the rest
of the code won’t be executed .
173 | P a g e
Ex:-
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("durga");
System.exit(0);------>line 1
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
System.out.println("u r getting ae"+ae);
System.exit(0);------>line 2
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code");
}
}
Note:- if we are commenting line 2
Output :- durga
174 | P a g e
Ex 1:-
try
{
AE
NPE
AIOBE Ex 2:-
} try
catch (AE e) {
{ AE
} NPE
catch (NPE e) AIOBE
{ }
} catch (Exception e)
catch (AIOBE e) {
{ }
}
Ex 4:-introduced in 1.7 version
Ex 3:- try
try {
{ AE
AE NPE
NPE AIOBE
AIOBE CCE
} }
catch (AE e) catch (AE|NPE e)
{ {
} }
catch (Exception e) catch (AIOBE|CCE e)
{ {
} }
Throw:-
1) The main purpose of the throw keyword is to creation of Exception object explicitly either for
predefined or user defined .
2) Throw keyword works like a try block. The difference is try block is automatically find the
situation and creates a Exception object implicitly. Whereas throw keyword creates a Exception
object explicitly.
Ex:-
class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
175 | P a g e
}
catch (ArithmeticException ae)
{
System.out.println("we are getting Exception "+ae);
}
}
}
Output:- we are getting Exception ArtithmeticException: / by zero
Note :-
In the above program the main method is responsible to create a exception object. So the main
method is creating exception object implicitly. The programmer is not responsible person to creates a
exception object.
Ex:-
class Test
{
public static void main(String[] args)
{
throw new ArithmeticException("we are getting Exception / by zero man");
}
}
Output:-
Exception in Thread “main” :java.lang.ArithmeticException:we are getting Exception/ by zero man
Note:-
In the above program the programmer is creating exception object explicitly. The main method
is not responsible person to creates exception object.
Ex:-
import java.util.*;
class Test
{
static void validate(int age)
{
if (age<18)
{
throw new ArithmeticException("not elgible for vote");
}
else
{
System.out.println("welcome to the voteing");
}
}
176 | P a g e
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int n=s.nextInt();
validate(n);
System.out.println(“rest of the code”);
}
}
Throws :-
1) Throw keyword is used to create exception object explicitly. But the main purpose of the throws
keyword is bypassing the generated exception from present method to caller method.
2) Throw keyword is used in the method body. But throws keyword we have to use in the method
declaration.
3) It is possible to throws any number of exceptions at a time based on the programmer
requirement.
In the java language we are handling the Exception in two ways
1) By using try-catch blocks
2) By using throws keyword
177 | P a g e
By using throws keyword:-
Ex 1:-
import java.io.*;
class Student
{
void studentDetails()throws IOException
{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("please enter student name");
String sname=br.readLine();
System.out.println("u r name is:"+sname);
}
public static void main(String[] args)throws IOException
{
Student s1=new Student();
s1.studentDetails();
}
}
Ex 2:-
import java.io.*;
class Student
{
void studentDetails()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("please enter student name");
String sname=br.readLine();
System.out.println("u r name is:"+sname);
}
public static void main(String[] args)
{
Student s1=new Student();
try
{
s1.studentDetails();
}
catch (IOException ie)
{
System.out.println("this is my handling code");
}
}
}
Ex 3:-
import java.io.*;
class Student
{
void studentDetails()throws IOException
178 | P a g e
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("please enter student name");
String sname=br.readLine();
System.out.println("please enter student rollno");
int sroll=Integer.parseInt(br.readLine());
System.out.println("enter student address");
String saddr=br.readLine();
System.out.println("student name is:"+sname);
System.out.println("student rollno is:"+sroll);
System.out.println("student address is:"+saddr);
}
void principal() throws IOException
{
studentDetails();
}
void officeBoy()throws IOException
{
principal();
}
Exceptions:-
There are two types of exceptions present in the java language
1) Predefined Exceptions.
2) User defined Exceptions.
Predefined Exception:-
Predefined classes comes along with the software based on your requirement we have to create
a objects.
Ex:- ArithmeticException,IOException,NullPointerException…………..etc
User defined Exceptions:-
Based on the user requirement user can creates a Exception is called user defined Exception.
Ex:InvaliedAgeException,BombBlostException………..etc
179 | P a g e
4) the naming conventions we have to fallow
a. every exception suffix must be the word Exception.
b. Exception in a class so we have to fallow class coding conventions.
for the creation of UncheckedException:-
180 | P a g e
}
//program that uses user defined Exception class
import java.util.*;
class Test
{
static void validate(int age) throws InvaliedAgeException
{
if (age<18)
{
throw new InvaliedAgeException("not elgible for vote");
}
else
{
System.out.println("welcome to the voteing");
}
}
public static void main(String[] args) throws InvaliedAgeException
{
Scanner s=new Scanner(System.in);
System.out.println("please enter age");
int age=s.nextInt();
validate(age);
}
}
Ex:-preparation of custom unchecked exceptions:-
import java.util.*;
class Test
{
static void validate(int age)
{
if (age<18)
{
throw new InvaliedAgeException("not elgible for vote");
}
else
{
System.out.println("welcome to the voteing");
}
}
181 | P a g e
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("please enter age");
int age=s.nextInt();
validate(age);
}
}
182 | P a g e
String str1="abc";
int b=Integer.parseInt(str1);
System.out.println(b);//NumberFormatException
}
catch (NumberFormatException ae)
{
System.out.println("boss u r geting NumberFormatException");
System.out.println("check once u r code");
}
}
}
NullPointerException:-
If we are having ‘null’ in any variable in that variable we are performing any operation we are
getting NummpointerException.
Ex:-
class Test
{
public static void main(String[] args)
{
try
{
String str="rattaiah";
System.out.println(str.length());//8
String str1=null;
System.out.println(str1.length());//NullPointerException
}
catch (NullPointerException ne)
{
System.out.println("boss u r geting nullpointerexception");
System.out.println("check once u r code");
}
}
}
ArithmeticException:-
Whenever we are performing / by zero operation we are getting ArithmeticException.
Ex:-
class Test
{
public static void main(String[] args)
{
try
{
int a=10/2;
System.out.println(a);//5
183 | P a g e
int b=10/0;
System.out.println(b);//ArithmeticExceptiom
}
catch (ArithmeticException ne)
{
System.out.println("boss u r geting ArithmeticException");
System.out.println("check once u r code");
}
}
}
IllegalArgumentException:-
Thread priority range is 1-10
1---low priority
10-high priority
If we are giving priority out of range then we are getting IllegalArgumentException.
Ex:-
class Test
{
public static void main(String[] args)
{
Thread t=new Thread();
t.setPriority(11);//IllegalArgumentException
}
}
IllegalThreadStateException:-
Whenever we are trying to restart the already start thread then we are getting
IllegalThreadStateException.
Ex:-
class Test
{
public static void main(String[] args)
{
Thread t=new Thread();
t.start();
t.start();//IllegalThreadStateException
}
}
StringIndexOutOfBoundsException:-
Whenever we are trying to perform String based operations with out of range condition then we
will get StringIndexOutOfBoundsException.
Ex:-
class Test
{
public static void main(String[] args)
184 | P a g e
{
String str="rattaiah";
System.out.println(str.charAt(3));//t
System.out.println(str.charAt(13));//StringIndexOutOfBoundsException
}
}
NegativeArraySizeException:-
If we are giving array size in negative values then we are getting NegativeArraySizeException.
Ex:-
class Test
{
public static void main(String[] args)
{
int[] a1=new int[100];
System.out.println(a1.length);//100
int[] a=new int[-9];
System.out.println(a.length);//NegativeArraySizeException
}
}InputMismatchException:-
import java.util.*;
class Test
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("enter first number");
int a=s.nextInt();
System.out.println("enter second number");
int b=s.nextInt();
System.out.println(a+b);
}
};
185 | P a g e
Different types of Errors:-
StackOverflowError:-
Whenever we are calling method recursively then we are getting StackOverflowError.
Ex:-
class Test
{
void m1()
{
m2();
System.out.println("this is Rattaiah");
}
void m2()
{
m1();
System.out.println("from durgasoft");
}
public static void main(String[] args)
{
Test t=new Test();
t.m1();
}
}
OutOfMemoryError:-
If we are creating objects greater than the heap memory then we are getting
OutOfMemoryError.
Ex:-
class Test
{
public static void main(String[] args)
{
int[] a=new int[100000000];//OutOfMemoryError
}
}
NoClassDefFoundError:-
Whatever the class if we want to execute if the class is not available at runtime we are getting
NoClassDefFoundError.
Ex:-
class Test
{
public static void main(String[] args)
{
System.out.println("rattaiah");
}
}
Output:- javac Test.java
Java Test
186 | P a g e
o/p:-Rattaiah
if we are executing class ABC (java ABC) if that class is not available then we are getting
NoClassDefFoundError .
java 7 features:-
multi-catch:-
the multi-catch feature is allows two or more exceptions to be caught by the same catch clause.
import java.util.*;
class Test
{
public static void main(String[] args)
{
int a[]=new int[3];;
Scanner s=new Scanner(System.in);
System.out.println("enter n value");
int n=s.nextInt();
try
{
System.out.println(10/n);
for (int i=0;i<a.length;i++ )
{
System.out.println("enter "+i+" value");
a[i]=s.nextInt();
}
System.out.println(a[7]);
}
catch (ArithmeticException|ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("program is ended");
}
};
187 | P a g e