Java try Keyword
Usage and Examples

try Keyword in Java

In Java, the try keyword is a foundational part of the language’s exception handling system. It is used to define a block of code that might throw an exception during execution. This mechanism allows developers to anticipate potential issues and handle them gracefully, avoiding abrupt program termination.

Purpose of try in Java

The try block is where you place code that you suspect might throw an exception. If an exception occurs, the control is immediately transferred to the corresponding catch block. If no exception occurs, the catch block is skipped.

Basic Syntax of try in Java

try {
    // Code that might throw an exception
} catch (ExceptionType name) {
    // Code that handles the exception
}

Simple Example with Explanation

public class TryExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will throw ArithmeticException
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        }
    }
}
Cannot divide by zero!

In this example, the line 10 / 0 causes an ArithmeticException. Java skips the remaining lines inside the try block and jumps directly to the catch block.

Try with Multiple Catch Blocks

You can handle different types of exceptions using multiple catch blocks. Java checks them in order, and the first matching block is executed.

public class MultipleCatchExample {
    public static void main(String[] args) {
        try {
            String text = null;
            System.out.println(text.length()); // NullPointerException
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic error");
        } catch (NullPointerException e) {
            System.out.println("Null pointer error");
        }
    }
}
Null pointer error

Using finally with try

The finally block is used for code that should run regardless of whether an exception occurred or not. It's often used to release resources like files or database connections.

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int[] arr = {1, 2, 3};
            System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Index out of bounds!");
        } finally {
            System.out.println("This always executes.");
        }
    }
}
Index out of bounds!
This always executes.

Try-with-Resources

Java 7 introduced try-with-resources for automatically closing resources such as file streams. Any class implementing AutoCloseable can be used.

import java.io.*;

public class TryWithResourcesExample {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
            System.out.println(br.readLine());
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file.");
        }
    }
}

In this example, the BufferedReader is automatically closed after use, even if an exception occurs. This reduces the need for an explicit finally block.

Key Points to Remember

  • try must be followed by at least one catch or finally block.
  • Only code that might throw an exception should go inside try.
  • finally always executes, regardless of exceptions.
  • Using specific exception types in catch improves clarity and precision.