Java Try-Catch Block: Handling Exceptions in Java

Learn how to effectively handle exceptions in Java using the try and catch blocks. This guide explains the syntax and best practices for preventing your program from crashing due to runtime errors and ensuring smooth execution.



Java Try-Catch Block

An exception, often referred to as an exceptional event, occurs during the execution of a program when something goes wrong. When an exception is thrown, it disrupts the normal flow of the program, potentially causing it to terminate unexpectedly. To prevent this, exceptions must be handled appropriately.

Understanding Try and Catch

In Java, exceptions can be caught using a combination of the try and catch keywords. A try and catch block surrounds the code that may generate an exception. The code within these blocks is known as protected code. The syntax for using try/catch is as follows:

Syntax

try {
// Protected code
} catch (ExceptionType e) {
// Catch block
}

The Try Block

The try block contains code that may throw an exception. If an exception occurs within this block, it is caught by the corresponding catch block. Every try block must be followed immediately by either a catch block or a finally block.

The Catch Block

A catch block declares the type of exception to be handled. If an exception occurs in the protected code, the catch block(s) following the try block are examined. If the type of exception matches one of the catch blocks, the exception is passed to that block, similar to how arguments are passed to method parameters.

Example of Java Try and Catch Block

In the following example, we declare an array with 2 elements and attempt to access the 3rd element, which causes an exception. The code is enclosed in a try block, allowing the exception to be caught in the subsequent catch block, which is designed to handle ArrayIndexOutOfBoundsException. After catching the exception, we can print the details of the thrown exception.

Code Example

package com.tutorialsarena;

public class ExcepTest {
public static void main(String args[]) {
    try {
        int a[] = new int[2];
        System.out.println("Access element three: " + a[3]);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Exception thrown: " + e);
    }
    System.out.println("Out of the block");
}
}
Output

Exception thrown: java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
Out of the block

Multiple Catch Blocks in Java

A single try block can be followed by multiple catch blocks. The syntax for using multiple catch blocks is as follows:

Syntax: Multiple Catch Blocks

try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}

This example demonstrates three catch blocks; however, any number can follow a single try. If an exception occurs, it is thrown to the first catch block in the list. If the exception type matches ExceptionType1, it is caught there. If not, it is passed to the next catch block and continues until it either is caught or falls through all the catch blocks, at which point the method stops execution and the exception propagates back up the call stack.

Example: Multiple Catch Blocks

In the following example, an error occurs due to division by zero. The exception is not an ArrayIndexOutOfBoundsException, so the next catch block handles the exception and prints its details.

Code Example

package com.tutorialsarena;

public class ExcepTest {
public static void main(String args[]) {
    try {
        int a[] = new int[2];
        int b = 0;
        int c = 1 / b;
        System.out.println("Access element three: " + a[3]);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("ArrayIndexOutOfBoundsException thrown: " + e);
    } catch (Exception e) {
        System.out.println("Exception thrown: " + e);
    }
    System.out.println("Out of the block");
}
}
Output

Exception thrown: java.lang.ArithmeticException: / by zero
Out of the block

Catching Multiple Exceptions with Java Try and Catch Block

Since Java 7, you can handle multiple exceptions with a single catch block, simplifying your code. Here’s how it works:

Syntax: Catching Multiple Exceptions

catch (IOException | FileNotFoundException ex) {
logger.log(ex);
throw ex;
}

Example: Catching Multiple Exceptions

The following code segment demonstrates how to catch multiple exceptions in a single catch statement. Here, we generate an error by dividing a value by zero while simultaneously handling ArrayIndexOutOfBoundsException and ArithmeticException.

Code Example

package com.tutorialsarena;

public class ExcepTest {
public static void main(String args[]) {
    try {
        int a[] = new int[2];
        int b = 0;
        int c = 1 / b;
        System.out.println("Access element three: " + a[3]);
    } catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
        System.out.println("Exception thrown: " + e);
    }
    System.out.println("Out of the block");
}
}
Output

Exception thrown: java.lang.ArithmeticException: / by zero
Out of the block