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
- Agar try block me exception nahi aata to catch block skip hota hai aur finally block execute hota hai.
- Agar try me exception aata hai aur catch block us exception ko handle karta hai to catch block execute hota hai, phir finally block bhi.
- Agar exception catch block me handle nahi hota to program terminate hota hai, par finally block tab bhi execute hota hai.
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
- Try block ke bina catch ya finally block use nahi kar sakte.
- Catch block multiple bhi ho sakte hain.
- Finally block optional hai, lekin agar diya gaya hai to try-catch ke baad hi hona chahiye.
- Finally block me jo code hota hai vo hamesha execute hota hai, even if return statement try ya catch me ho.