হ্যাঁ, জাভাতে একটি ট্রাই ব্লকের সাথে একাধিক ক্যাচ ব্লক ব্যবহার করা যায়।
- প্রতিটি ট্রাই ব্লকের সাথে কমপক্ষে একটি ক্যাচ ব্লক থাকতে হয়।
- ট্রাই ব্লকে এক্সেপশন অবজেক্ট সনাক্ত হলে এবং একাধিক ক্যাচ ব্লক থাকলে, ক্যাচ ব্লকগুলোর প্রাধান্য সংজ্ঞার ক্রম অনুযায়ী নির্ধারিত হয়।
- সর্বোচ্চ প্রাধান্য প্রথম ক্যাচ ব্লকে দিয়ে থাকে। যদি প্রথম ক্যাচ ব্লক এক্সেপশন হ্যান্ডেল না করতে পারে, তবে পরবর্তী ক্যাচ ব্লক বিবেচনা করা হয়।
উদাহরণ
class TryWithMultipleCatch {
public static void main(String args[]) {
try {
int a[] = new int[5];
a[3] = 10 / 0;
System.out.println("First print statement in try block");
} catch (ArithmeticException e) {
System.out.println("Warning: ArithmeticException");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Warning: ArrayIndexOutOfBoundsException");
} catch (Exception e) {
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block");
}
}
আউটপুট
Warning: ArithmeticException
Out of try-catch block