ได้ เราสามารถกำหนดบล็อกลองหนึ่งบล็อกด้วยบล็อก catch หลายอันใน Java
- ทุกความพยายามควรและต้องเชื่อมโยงกับบล็อก catch อย่างน้อยหนึ่งบล็อก
- เมื่อใดก็ตามที่ระบุอ็อบเจ็กต์ข้อยกเว้นในบล็อกการลอง และหากมีบล็อก catch หลายอัน ลำดับความสำคัญสำหรับบล็อก catch จะได้รับตามลำดับที่มีการกำหนดบล็อก catch ไว้
- ลำดับความสำคัญสูงสุดจะมอบให้กับบล็อก catch แรกเสมอ หากบล็อก catch แรกไม่สามารถจัดการวัตถุยกเว้นที่ระบุได้ จะพิจารณาบล็อก catch ถัดไปทันที
ตัวอย่าง
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