← Back to Core Java Course | Chapter 10: Exception Handling | Lesson 2 of 8

Java try-catch

The try Block

The try block wraps the specific lines of code you suspect might throw an exception. Java only starts checking for exceptions once execution enters this block; code outside it isn't protected.

Example: The try Block

java
public class Main {
	public static void main(String[] args) {
		try {
			int result = 10 / 0; // suspected risky code
			System.out.println(result);
		} catch (ArithmeticException e) {
			System.out.println("Error caught");
		}
	}
}

The catch Block

A catch block catches one exception type and runs its recovery logic if a matching exception is thrown inside the paired try. If no exception occurs, the entire catch block is skipped.

Example: The catch Block

java
public class Main {
	public static void main(String[] args) {
		try {
			int result = 10 / 2;
			System.out.println(result);
		} catch (ArithmeticException e) {
			System.out.println("This is skipped: no exception occurred");
		}
	}
}

Multiple Catch Blocks

You can chain several catch blocks after one try to handle different exception types differently — a FileNotFoundException might prompt the user to pick a new file, while an IOException might just log and retry. Java checks them top to bottom and runs only the first match.

Example: Multiple Catch Blocks

java
public class Main {
	public static void main(String[] args) {
		try {
			int[] arr = new int[2];
			System.out.println(arr[5]);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("Index error");
		} catch (NullPointerException e) {
			System.out.println("Null error");
		}
	}
}

Multi-Catch Block

A multi-catch block (catch (IOException | SQLException e)) lets one block handle several unrelated exception types identically, avoiding duplicated recovery code when the response would be the same either way. The caught variable's type is the common supertype of the listed exceptions.

Example: Multi-Catch Block

java
public class Main {
	public static void main(String[] args) {
		try {
			throw new NumberFormatException("bad number");
		} catch (NumberFormatException | NullPointerException e) {
			System.out.println("Handled: " + e.getMessage());
		}
	}
}

Nested try-catch Blocks

You can nest a try-catch inside another try block when an inner operation needs its own, more specific error handling separate from the outer block's broader recovery logic. This is common when a single risky call sits inside a larger risky operation.

Example: Nested try-catch Blocks

java
public class Main {
	public static void main(String[] args) {
		try {
			try {
				int result = 10 / 0;
			} catch (ArithmeticException e) {
				System.out.println("Inner catch");
			}
		} catch (Exception e) {
			System.out.println("Outer catch");
		}
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.