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. This is a foundational concept in enterprise application development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Java experience. Take your time with each section and practice the examples
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
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!");
}
}