Java

What are try and catch blocks in exception handling4 min read

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 tryblock 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:

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 catchblock 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

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 catchblocks:

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:

The above program when compiled will generate errors as the second and third catch blocks are non-reachable. To eliminate errors place the Exceptioncatch 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:

Notice that in the above program the catch block of inner try is handling ArithmeticException which is not supposed to raise in the inner tryblock. 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.

Take your time to comment on this article.

Leave a Comment