Java Try, Catch and Finally Blocks - Detailed Explanation

Try Block

Try block mein aise code likhte hain jisme exceptions ke chances hote hain. Java runtime jab try block ke code ko execute karta hai aur koi exception aata hai to turant try block ka execution ruk jata hai, aur exception handling block (catch) ki taraf control chala jata hai.

try {
    // Code that may throw an exception
    int result = 10 / 0; // ArithmeticException
}

Catch Block

Catch block try me aaye exception ko handle karta hai. Agar exception throw hota hai, to catch block ka code execute hota hai. Catch ke andar hum exception object use kar sakte hain jaise error messages print karne ke liye.

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero.");
}

Finally Block

Finally block aisi code ko rakha jata hai jo try aur catch blocks ke baad hamesha execute hota hai chaahe exception aaye ya naa aaye. Iska use zyadaatar cleanup kaam ke liye hota hai jaise file close karna ya resource release karna.

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero.");
} finally {
    System.out.println("This will always execute.");
}

Flow of Control

Example: Try-Catch-Finally

public class TryCatchFinallyDemo {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds!");
        } finally {
            System.out.println("Finally block executed.");
        }
        System.out.println("Program continues...");
    }
}

Output:

Array index is out of bounds!
Finally block executed.
Program continues...

Important Notes