Try-Catch-Finally Blocks
Exception handling lets you gracefully handle errors without crashing. The try-catch-finally structure catches exceptions, handles them, and ensures cleanup code runs regardless of whether an error occurred.
40 min•By Priygop Team•Last updated: Feb 2026
How Try-Catch Works
When code inside a 'try' block throws an exception (error), Java immediately jumps to the matching 'catch' block instead of crashing the program. The 'finally' block (optional) always runs — whether an exception occurred or not — perfect for cleanup like closing files or database connections.
Try-Catch-Finally Examples
Example
public class ExceptionDemo {
public static void main(String[] args) {
// Basic try-catch
try {
int result = 10 / 0; // ArithmeticException!
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
System.out.println("Details: " + e.getMessage());
}
// Multiple catch blocks
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException!
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
// Try-catch-finally
System.out.println("\n=== With Finally ===");
try {
System.out.println("Opening resource...");
String text = null;
System.out.println(text.length()); // NullPointerException!
} catch (NullPointerException e) {
System.out.println("Error: Null value encountered!");
} finally {
System.out.println("Cleanup: Resource closed."); // Always runs!
}
// Number parsing
String[] inputs = {"42", "hello", "99", "3.14"};
for (String input : inputs) {
try {
int num = Integer.parseInt(input);
System.out.println("Parsed: " + num);
} catch (NumberFormatException e) {
System.out.println("'" + input + "' is not a valid integer");
}
}
System.out.println("\nProgram continues normally!");
}
}Try It Yourself: Safe Calculator
Try It Yourself: Safe CalculatorJava
Java Editor
✓ ValidTab = 2 spaces
Java|41 lines|1397 chars|✓ Valid syntax
UTF-8