Java Docs

Java Documentation

Java try...catch Blocks

The try...catch block in Java is used to handle exceptions and prevent the abnormal termination of a program.

Syntax of try...catch

try {
  // code
} catch(Exception e) {
  // handle exception
}

Example: Java try...catch block

class Main {
  public static void main(String[] args) {
    try {
      int divideByZero = 5 / 0;
      System.out.println("Rest of code in try block");
    } catch (ArithmeticException e) {
      System.out.println("ArithmeticException => " + e.getMessage());
    }
  }
}

Output

ArithmeticException => / by zero

try...finally Block

The finally block always executes, whether an exception occurs or not.

class Main {
  public static void main(String[] args) {
    try {
      int divideByZero = 5 / 0;
    } finally {
      System.out.println("Finally block is always executed");
    }
  }
}

Output

Finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero

try...catch...finally Block

You can also use a finally block after a try...catch block to ensure cleanup code is executed.

import java.io.*;

class ListOfNumbers {
  private int[] list = {5, 6, 8, 9, 2};

  public void writeList() {
    PrintWriter out = null;
    try {
      System.out.println("Entering try statement");
      out = new PrintWriter(new FileWriter("OutputFile.txt"));
      for (int i = 0; i < 7; i++) {
        out.println("Value at: " + i + " = " + list[i]);
      }
    } catch (Exception e) {
      System.out.println("Exception => " + e.getMessage());
    } finally {
      if (out != null) {
        System.out.println("Closing PrintWriter");
        out.close();
      } else {
        System.out.println("PrintWriter not open");
      }
    }
  }
}

class Main {
  public static void main(String[] args) {
    ListOfNumbers list = new ListOfNumbers();
    list.writeList();
  }
}

Output

Entering try statement
Exception => Index 5 out of bounds for length 5
Closing PrintWriter

Multiple Catch Blocks

You can use multiple catch blocks to handle different exceptions differently.

class ListOfNumbers {
  public int[] arr = new int[10];
  public void writeList() {
    try {
      arr[10] = 11;
    } catch (NumberFormatException e1) {
      System.out.println("NumberFormatException => " + e1.getMessage());
    } catch (IndexOutOfBoundsException e2) {
      System.out.println("IndexOutOfBoundsException => " + e2.getMessage());
    }
  }
}

class Main {
  public static void main(String[] args) {
    ListOfNumbers list = new ListOfNumbers();
    list.writeList();
  }
}

Output

IndexOutOfBoundsException => Index 10 out of bounds for length 10

Catching Multiple Exceptions

Java SE 7+ allows catching multiple exceptions in a single catch block.

try {
  // code
} catch (ExceptionType1 | ExceptionType2 ex) {
  // handle multiple exceptions
}

Try-with-Resources Statement

The try-with-resources statement automatically closes resources at the end of the statement. This is also called automatic resource management.

try (PrintWriter out = new PrintWriter(new FileWriter("OutputFile.txt"))) {
  // use the resource
} catch (Exception e) {
  // handle exception
}