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