Java try-catch
In this page:
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
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");
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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");
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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");
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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());
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: