In this article we will learn about try and catch blocks in more detail along with Java code examples.
A Simple try-catch Block
As we know, statements that might raise exceptions are placed inside try block and the exception handling code is placed inside catch block. A try block must be followed immediately by one or more catch blocks or a finally block.
Let’s see an example program which catches an array index out of bounds exception:
class ArrayException
{
public static void main(String[] args)
{
try
{
int a[] = {1, 2, 3};
System.out.println("Value is: " + a[4]);
System.out.println("Another print statement!");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("Outside try-catch block");
}
}
Output of the above program is:
java.lang.ArrayIndexOutOfBoundsException: 4
Outside try-catch block
Whenever an exception is raised in one of the statements of try block, control automatically enters a subsequent catch block. After the code in the catch block completes execution, the control moves to the next statement after the try-catch block.
In the above catch block ‘e’ represents the exception object. When printed in the println() method, the toString() method executes which in turn gives the exception related information.
Multiple catch Blocks
A try block can be followed by multiple catch blocks to catch different types of exceptions in the code. Let’s look at a Java program which uses multiple catch blocks:
import java.util.Scanner;
class ArrayException
{
public static void main(String[] args)
{
try
{
Scanner input = new Scanner(System.in);
int x = 10;
int y = input.nextInt();
int z = x / y;
System.out.println("z = " + z);
int a[] = {1, 2, 3};
System.out.println("Value is: " + a[4]);
System.out.println("Another print statement!");
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("Outside try-catch block");
}
}
Output of the above program when z is given the value 2 by the user is:
z = 5
java.lang.ArrayIndexOutOfBoundsException: 4
Outside try-catch block
Output of the above program when z is given the value 0 by the user is:
java.lang.ArithmeticException: / by zero
Outside try-catch block
When using multiple catch blocks care should be taken that the order of exception classes must be from sub classes to the super class Exception. For example if the above program is modified as follows:
import java.util.Scanner;
class ArrayException
{
public static void main(String[] args)
{
try
{
Scanner input = new Scanner(System.in);
int x = 10;
int y = input.nextInt();
int z = x / y;
System.out.println("z = " + z);
int a[] = {1, 2, 3};
System.out.println("Value is: " + a[4]);
System.out.println("Another print statement!");
}
catch(Exception e)
{
System.out.println(e);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("Outside try-catch block");
}
}
The above program when compiled will generate errors as the second and third catch blocks are non-reachable. To eliminate errors place the Exception catch block as the last catch block.
Nested try Blocks
In Java, try blocks can be nested in one another. In nested try blocks, an exception raised in the inner try block can be handled by the catch blocks of outer try block. To understand this let’s look at the following example program:
import java.util.Scanner;
class ArrayException
{
public static void main(String[] args)
{
try
{
Scanner input = new Scanner(System.in);
int x = 10;
int y = input.nextInt();
int z = x / y;
System.out.println("z = " + z);
try
{
int a[] = {1, 2, 3};
System.out.println("Value is: " + a[4]);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("Another print statement!");
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("Outside try-catch block");
}
}
Notice that in the above program the catch block of inner try is handling ArithmeticException which is not supposed to raise in the inner try block. So, the array index out of bounds exception will be handled by the catch block of outer try block.
Output of the above program is:
z = 2
java.lang.ArrayIndexOutOfBoundsException: 4
Outside try-catch block
This is how we use try and catch blocks in Java.
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply