Unit-3
Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
In Java, an exception is an abnormal condition that disrupts the normal flow of the program.
Exception are the objects in java which is thrown at runtime.
Exception Handling is a mechanism to handle runtime abnormal situations which a program may
have to face, such as ClassNotFoundException, IOException, SQLException, RemoteException
Hierarchy of Java Exception classes
The [Link] class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following
table describes each.
Keyword Description
Try The "try" keyword is used to specify a block where we should place an exception code. It means
we can't use try block alone. The try block must be followed by either catch or finally.
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. It can be followed by finally block later.
Finally The "finally" block is used to execute the necessary code of the program. It is executed whether
an exception is handled or not.
Throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method signature.
Java Exception Handling Example
try-catch statement to handle the exception.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e)
{
[Link](e);
}
//rest code of the program
[Link]("rest of the code...");
}
}
Some examples of Java Exceptions
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
1. int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
1. String s=null;
2. [Link]([Link]());//NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has characters; converting this
variable into digit will cause NumberFormatException.
1. String s="abc";
2. int i=[Link](s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
try{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
//Write Code to handle the exception
}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.
The catch block must be used after the try block only. You can use multiple catch block with a
single try block.
Internal Working of Java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed.
Example
[Link]
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}
Output:
[Link]: / by zero
rest of the code
As displayed in the above example, the rest of the code is executed, i.e., the rest of the code statement is
printed.
Example 3
In this example, we also kept the code in a try block that will not throw an exception.
[Link]
public class TryCatchExample3 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
[Link]("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
Output:
[Link]: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will not
execute.
Example 4
Here, we handle the exception using the parent class exception.
[Link]
public class TryCatchExample4 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
[Link](e);
[Link]("Can't divided by zero");
}
[Link]("rest of the code");
}
}
Output:
[Link]: / by zero
rest of the code
Example 5
example to handle another unchecked exception.
[Link]
public class TryCatchExample9 {
public static void main(String[] args) {
try
{
int arr[]= {1,3,5,7};
[Link](arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
}
Output:
[Link]: 10
rest of the code
Java Catch Multiple Exceptions
Java Multiple-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
● At a time only one exception occurs and at a time only one catch block is executed.
● All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Example 1
Let's see a simple example of java multi-catch block.
[Link]
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
[Link]
public class MultipleCatchBlock3 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
[Link](a[10]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Example 4
In this example, we generate NullPointerException, but didn't provide the corresponding
exception type. In such case, the catch block containing the parent exception class Exception
will invoked.
[Link]
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{
String s=null;
[Link]([Link]());
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Parent Exception occurs
rest of the code
Java Nested try block
In Java, using a try block inside another try block is permitted. It is called as nested try block.
Syntax:
//main try block
try
{
statement 1;
//try catch block within another try block
try
{
statement 2;
//try catch block within nested try block
}
catch(Exception e2)
{
//exception message
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
Example [Link]
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
[Link](e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}
[Link]("normal flow..");
}
}
When any try block does not have a catch block for a particular exception, then the catch block
of the outer (parent) try block are checked for that exception, and if it matches, the catch block of
outer try block is executed.
If none of the catch block specified in the code is unable to handle the exception, then the Java
runtime system will handle the exception. Then it displays the system generated message for that
exception.
Java finally block
Java finally block is a block used to execute important code such as closing the connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception occurs or
not.
The finally block follows the try-catch block.
Why use Java finally block?
o finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
o The important statements to be printed can be placed in the finally block.
Usage of Java finally
Let's see the different cases where Java finally block can be used.
Case 1: When an exception does not occur
Let's see the below example where the Java program does not throw any exception, and the
finally block is executed after the try block.
Example of Finally block
[Link]
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
[Link](data);
}
//catch won't be executed
catch(NullPointerException e){
[Link](e);
}
//executed regardless of exception occurred or not
finally {
[Link]("finally block is always executed");
}
[Link]("rest of code...");
}
}
Output:
finally block is always executed
rest of code…
Case 2: When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however the catch block
cannot handle it. Despite this, the finally block is executed after the try block and then the
program terminates abnormally.
[Link]
public class TestFinallyBlock1{
public static void main(String args[]){
try {
[Link]("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
[Link](data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
[Link](e);
}
//executes regardless of exception occured or not
finally {
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
Output:
Case 3: When an exception occurs and is handled by the catch block
Example:
Let's see the following example where the Java code throws an exception and the catch block
handles the exception. Later the finally block is executed after the try-catch block. Further, the
rest of the code is also executed normally.
[Link]
public class TestFinallyBlock2{
public static void main(String args[]){
try {
[Link]("Inside try block");
//below code throws divide by zero exception
int data=25/0;
[Link](data);
}
//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e){
[Link]("Exception handled");
[Link](e);
}
//executes regardless of exception occured or not
finally {
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if the program exits (either by calling [Link]()
or by causing a fatal error that causes the process to abort).
Java throw keyword
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. It is mainly used to throw a custom exception.
We can also define our own set of conditions and throw an exception explicitly using throw
keyword. For example, we can throw ArithmeticException if we divide a number by another
number. Here, we just need to set the condition and throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
1. throw new exception_class("error message");
Java throw keyword Example
In this example, we have created a method named validate() that accepts an integer as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
[Link]("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
[Link]("rest of the code...");
}
}
we can also throw user defined exceptions as well as built in exception.
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide the
exception handling code so that the normal flow of the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not
checking the code before it being used.
Syntax of Java throws
1. return_type method_name() throws exception_class_name{
2. //method code
3. }
Advantage of Java throws keyword
It provides information to the caller of the method about the exception.
Java throws Example
[Link]
import [Link];
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){[Link]("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
[Link]("normal flow...");
}
}
Output:
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught or declare the
exception.
Difference between throw and throws in Java
The throw and throws is the concept of exception handling where the throw keyword throw the
exception explicitly from a method or a block of code whereas the throws keyword is used in
signature of the method.
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
Sr. Basis of Differences Throw throws
no.
1. Definition Java throw keyword is used Java throws keyword is used in
throw an exception explicitly the method signature to declare
in the code, inside the an exception which might be
function or the block of code. thrown by the function while the
execution of the code.
2. Type of exception Using throw Using throws keyword, we
keyword, we can only propagate can declare both checked and
unchecked exception i.e., the unchecked exceptions.
checked exception cannot be However, the throws keyword
propagated using throw only. can be used to propagate
checked exceptions only.
3. Syntax The throw keyword is The throws keyword is followed
followed by an instance of by class names of Exceptions to
Exception to be thrown. be thrown.
4. Declaration throw is used within the throws is used with the method
method. signature.
5. Internal implementation We are allowed to throw only We can declare multiple
one exception at a time i.e. we exceptions using throws
cannot throw multiple keyword that can be thrown by
exceptions. the method. For example,
main() throws IOException,
SQLException.
Java throw Example
public class A {
public static void display() {
try
{
throw new ArithmeticException("\ndivide by zero");
}
catch(ArithmeticException e)
{
[Link](e);
}
}
//main method
public static void main(String[] args) {
A obj = new A();
[Link]();
[Link]("Rest of the code..");
}
}
Java throws Example
public class Test {
public static int divide(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
//main method
public static void main(String[] args) {
Test obj = new Test();
try {
[Link]([Link](45, 0));
}
catch (ArithmeticException e){
[Link]("\nNumber cannot be divided by 0");
}
[Link]("Rest of the code..");
}
}
Difference between final, finally and finalize
The final, finally, and finalize are keywords in Java that are used in exception handling. Each of
these keywords has a different functionality. The basic difference between final, finally and
finalize is that the final is an access modifier, finally is the block in Exception Handling
and finalize is the method of object class.
Along with this, there are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:
Sr. Key Final finally finalize
no.
1. Definition final is the keyword and finally is the block in Java finalize is the method in Java
access modifier which is Exception Handling to which is used to perform
used to apply restrictions execute the important code clean up processing just
on a class, method or whether the exception before object is garbage
variable. occurs or not. collected.
2. Applicable Final keyword is used with Finally block is always finalize() method is used
to the classes, methods and related to the try and catch with the objects.
variables. block in exception
handling.
3. Functionality (1) Once declared, final (1) finally block runs the finalize method performs the
variable becomes constant important code even if cleaning activities with
and cannot be modified. exception occurs or not. respect to the object before
(2) final method cannot be (2) finally block cleans up its destruction.
overridden by sub class. all the resources used in try
(3) final class cannot be block
inherited.
4. Execution Final method is executed Finally block is executed as finalize method is executed
only when we call it. soon as the try-catch block just before the object is
is executed. destroyed.
It's execution is not
dependant on the exception.
Java finalize Example
[Link]
public class FinalizeExample {
public static void main(String[] args)
{
FinalizeExample obj = new FinalizeExample();
// printing the hashcode
[Link]("Hashcode is: " + [Link]());
obj = null;
// calling the garbage collector using gc()
[Link]();
[Link]("End of the garbage collection");
}
// defining the finalize method
protected void finalize()
{
[Link]("Called the finalize() method");
}
}
User Defined Exception/Custom exception
In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own
Exception is known as user-defined exception.
In order to create user defined exception, we need to extend Exception class that belongs to [Link]
package.
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class Test
{
static void display (int age) throws InvalidAgeException{
if(age < 0){
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid ");
}
else {
[Link]("welcome ");
}
}
// main method
public static void main(String args[])
{
try
{
display(-5);
}
catch (InvalidAgeException ex)
{
[Link]("in valid age Caught the exception");
[Link]("Exception occured: " + ex);
}
[Link]("rest of the code...");
}
}