23-Exception Handling in Java PDF
23-Exception Handling in Java PDF
Exception
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed. If we perform exception handling, the rest of the statement will be executed. That
is why we use exception handling in Java.
1. ArithmeticException
It is caused by math errors such as division by zero.
2. NullPointerException
If object is declared but memory is not allocated.
3. ArrayIndexOutOfBoundsException
It is caused by bad array index.
4. FileNotFoundExcetption
It is caused by an attempt to access a non existing file.
5. IOException
It is caused by general Input/Output failure, such as inability to read from file.
6. NumberFormatException
It is caused when a conversion between String and number fails.
etc.
Exception Handling
Exception handling means if exception occur in your program, handle that situation and
continue the program execution by taking some necessary action.
Exception is a predefined class available in “java.lang” package.
Hierarchy of Java Exception classes
Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class in java.
Throwable class is the root class of Java Exception hierarchy which is inherited by two
subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:
Object
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1. Checked Exception
An exception that is checked by the compiler at the compilation time is called
checked exception.
These exceptions cannot be simply be ignored, the programmer should handle
these exception
IOException, SQLExcetption, IllegalThreadStateException etc are checked
exception.
Checked exception forces program to deal with the exception that may be throws
or with the help of try – catch block.
2. Unchecked Exception
An exception that occurs at the time of execution is called unchecked exception.
Unchecked exceptions are also called Runtime exception.
Runtime exceptions are ignored at the time of compilation.
ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of
the java.lang.RuntimeException class, which is subclass of Exception class.
Unchecked exceptions are basically built in exception in java.
1. try In try block you have to write those statements in which there is a
possibility of exception. The try block must be followed by either catch
or finally. It means, we can't use try block alone.
2. catch The "catch" block is used to handle the exception. It must be preceded
by try block which means we can't use catch block alone.
3. finally The "finally" block is used to execute the important code of the program.
It is executed whether an exception is handled or not.
(i)
import java.util.*;
class Test
{
public static void main(String args[])
{
System.out.println(3/0);
System.out.println("Thank you.");
}
}
(ii)
import java.util.*;
class Test
{
public static void main(String args[])
{
try
{
System.out.println(3/0);
}
catch(ArithmeticException ex)
{
System.out.println(“Exception:\t”+ex.getMessage());
}
System.out.println(“Thank you.”);
}
}
(iii)
import java.util.*;
class Test
{
public static void main(String args[])
{
int a,b,rs=0;
Scanner scan=new Scanner(System.in);
System.out.println(“Enter the First No:”);
a=scan.nextInt();
System.out.println(“Enter the Second No:”);
b=scan.nextInt();
try
{
rs=a/b;
}catch(ArithmeticException ex){ex.printStackTrace();}
System.out.println(“Result:\t”+rs);
}
}
System.out.println(“Result:\t”+rs);
}
}
Example of “ArrayIndexOutOfBoundsException” in java
(i)
import java.util.*;
class Test
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
int x=0;
try
{
x=a[5];
catch(ArrayIndexOutOfBoundsException ex)
{
//System.out.println("Array Index Error");
ex.printStackTrace();
}
System.out.println("X=\t"+x);
} //main close
} //class close
(ii)
import java.util.*;
class Test
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
int x=0;
try
{
x=a[2]/(a[1]-b);
}
catch(ArithmeticException ex)
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Array Index Error");
}
//int y=a[1]/a[0];
System.out.println("X=\t"+x);
} //main close
} //class close
(iii)
import java.util.*;
class Test
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
int x;
try
{
x=a[2]/a[1]-b;
}
catch(ArithmeticException ex)
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Array Index Error");
}
System.out.println();
System.out.println("X=\t"+x);
} //main close
} //class close
class Stud
{
int rno;
String name;
void display()
{
System.out.println(rno+"\t"+name);
}
try
{
Stud s=null;
s.set_data(1001,"manjeet");
s.display();
}
catch(NullPointerException ex){ex.printStackTrace();}
(ii)
class Stud
{
int rno;
String name;
void display()
{
System.out.println(rno+"\t"+name);
}
}
Example of “NumberFormatException” in java
import java.util.*;
class Test
{
public static void main(String args[])
{
int num;
try
{
num=Integer.parseInt("Manjeet");
}
catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("Thank you.");
} //main close
} //class close
(ii)
import java.util.*;
class Test
{
public static void main(String args[])
{
int num=0;
try
{
num=Integer.parseInt("10");
}
catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("Number is\t"+num);
System.out.println("Thank you.");
} //main close
} //class close
Throw in java
In java, throw keyword is used to explicitly throw an exception.
We can throw unchecked exception in java by throw keyword.
The throw keyword is mainly used to throw custom exception/user defined exception.
Syntax:
throw exception;
Eg:
Example:
import java.util.Scanner;
class TestThrow
{
public static void main(String args[])
{
try{
int age;
Scanner scan=new Scanner(System.in);
System.out.println("Enter the age:");
age=scan.nextInt();
if(age<18)
throw new ArithmeticException("Invalid age");
}
catch(ArithmeticException ex)
{
System.out.println("Exception:\t"+ex.getMessage());
}
}
}
Custom exception or User defined exception
Q: Write a java program to create AgeException class, raise the exception when a user
input age less than 18 or greater than 40.
Or
Write a java program to create Employee class with age as a attribute. If age is less than 18
or greater than 40 then throw AgeException.
Ans:
class Employee
{
int age;
void set_data(int a)
{
age=a;
}
void display()
{
try{
if(age<18||age>40)
throw new AgeException();
System.out.println(age);
}
catch(AgeException ex)
{
ex.disp();
}
}
Eg:
class Employee
{
int eid;
String name,dateOfBirth;
String ss[];
void display()
{
try{
if((Integer.parseInt(ss[0])<1) || (Integer.parseInt(ss[0])>31))
throw new DateException();
else if((Integer.parseInt(ss[1])<1) || (Integer.parseInt(ss[1])>12))
throw new DateException();
else if((Integer.parseInt(ss[2])<=2004))
throw new DateException();
System.out.println(eid+"\t"+name+"\t"+dateOfBirth);
}
catch(DateException ex)
{
ex.disp();
}
}
Throws Keyword
If any method is able to raise or generate an exception, but if it is not handled there and if you
want to handle that exception in calling method then in-front of method name mention the
possible exception list by using “throws” keyword.
Eg:
class Employee
{
int age;
void set_data(int a)
{
age=a;
}
if(age<18||age>60)
throw new AgeException();
System.out.println(age);
try{
Employee e=new Employee();
e.set_data(50);
e.display();
}
catch(AgeException ex)
{
ex.disp();
}
}
Throw Throws
1. Used to explicitly throw an Used to declare an exception.
exception.
2. Checked exceptions cannot be Checked exceptions can be propagated using
propagated using throw. throws
3. Followed by an instance. Followed by a class.
4. Used within a method. Used with a method signature.
5. Cannot throw multiple exception. Can declare multiple exception.
Finally keyword
In finally block you can write those statements which you want to execute in both situation,
exception generated or exception not generated. Finally block should be immediately after the try
block or catch block.
import java.util.Scanner;
class Test1
{
public static void main(String args[])
{
int a,b,rs=0;
Scanner scan=new Scanner(System.in);
try
{
a=scan.nextInt();
b=scan.nextInt();
rs=a/b;
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
System.out.println("Result:"+rs);
}
}
};
import java.util.Scanner;
class Test1
{
public static void main(String args[])
{
int a,b,rs=0;
Scanner scan=new Scanner(System.in);
try
{
a=scan.nextInt();
b=scan.nextInt();
rs=a/b;
}
finally
{
System.out.println("Result:"+rs);
}
};