Labs ICT
โญ Pro Login

Try & Catch

So now you know exceptions exist. The question is โ€” what do you do when one happens? You catch it using a try-catch block. This is how you handle errors gracefully without crashing your program.

The Try-Catch Block

You put the risky code inside a try block and the handling code inside a catch block. If no exception happens, the catch block is skipped.

public class Main {
  public static void main(String[] args) {
    try {
      int result = 10 / 0;
      System.out.println("This will not print");
    } catch (ArithmeticException e) {
      System.out.println("Cannot divide by zero");
    }
  }
}

When 10 / 0 executes, Java throws an ArithmeticException. The program jumps straight to the catch block and runs that code. The line after the division never executes.

Multiple Catch Blocks

Different exceptions need different handling. You can have multiple catch blocks for the same try block.

public class Main {
  public static void main(String[] args) {
    try {
      int[] nums = {1, 2, 3};
      int result = nums[5] / 0;
    } catch (ArithmeticException e) {
      System.out.println("Math error");
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Array index error");
    }
  }
}

Java checks the catch blocks in order. The first one that matches the exception type runs. The rest are skipped. In this case, nums[5] throws an ArrayIndexOutOfBoundsException first โ€” so that catch block runs and the ArithmeticException one never gets checked.

The finally Block

There is a third block you can add: finally. It runs no matter what โ€” whether an exception happened, whether you caught it, or even if you have a return statement in the try block.

public class Main {
  public static void main(String[] args) {
    try {
      System.out.println("In try");
      int result = 10 / 0;
    } catch (ArithmeticException e) {
      System.out.println("Caught error");
    } finally {
      System.out.println("This always runs");
    }
  }
}

finally is perfect for cleanup โ€” closing files, releasing network connections, or freeing up resources. No matter what happens in the try or catch, the finally block executes.

Try-With-Resources

Java 7 introduced a cleaner way to handle resources that need to be closed. Instead of manually closing things in a finally block, you declare the resource in the try parentheses and Java closes it automatically.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    try (Scanner sc = new Scanner(new File("data.txt"))) {
      while (sc.hasNextLine()) {
        System.out.println(sc.nextLine());
      }
    } catch (FileNotFoundException e) {
      System.out.println("File not found");
    }
  }
}

No finally needed. The Scanner is automatically closed when the try block finishes, whether normally or with an exception. Less code, fewer bugs, cleaner logic.

๐Ÿงช Quick Quiz

What does the finally block do?