☕ Java

try-catch-finally in Java

Things go wrong in real applications — files don't exist, networks time out, users enter garbage data. Exception handling is how you deal with these failures gracefully instead of crashing your whole program.

What is an Exception?

An exception is an unexpected event that disrupts normal program execution. Without handling them, your program crashes with a stack trace and leaves your users staring at an error screen. Real-world analogy: Think of exception handling like a try-catch in real life. You try to hail a taxi. If no taxi comes (exception), you have a backup plan: call an Uber. Either way, you get home — the error didn't ruin your evening. Java's exception handling lets you: • Try risky operations • Catch specific failures and respond appropriately • Guarantee cleanup code runs (closing files, releasing connections) even if something fails

try-catch-finally Structure

Java
public class FileProcessor {
    public static void main(String[] args) {
        try {
            // Code that might fail goes here
            int[] arr = new int[5];
            arr[10] = 42;  // This throws ArrayIndexOutOfBoundsException

        } catch (ArrayIndexOutOfBoundsException e) {
            // Handle this specific exception
            System.out.println("Array access error: " + e.getMessage());

        } catch (NullPointerException e) {
            // Multiple catch blocks for different exception types
            System.out.println("Null reference: " + e.getMessage());

        } catch (Exception e) {
            // Catch-all for anything we didn't specifically handle
            // Put this last — it catches everything
            System.out.println("Unexpected error: " + e.getMessage());

        } finally {
            // This ALWAYS runs — even if an exception occurred
            // Perfect for cleanup: close files, release DB connections
            System.out.println("Cleanup complete — this always runs");
        }
    }
}

Common Exceptions You'll Encounter

These aren't just theory — you will hit these in real development: • NullPointerException — The most famous Java exception. You tried to call a method on an object that's null. Always check for null before using optional values. • ArrayIndexOutOfBoundsException — You accessed index 5 on a 5-element array (max index is 4). Remember: arrays are 0-indexed. • ClassCastException — You tried to cast an object to an incompatible type: "(String) someIntegerObject" • NumberFormatException — Integer.parseInt("hello") throws this. Always validate user input before parsing. • ArithmeticException — Division by zero. Protect your division operations with a zero check. • NullPointerException in modern Java can often be avoided with Optional (see Java 8 Features section).