Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เราสามารถกำหนดบล็อก try พร้อมหลายบล็อก catch ใน Java ได้ไหม

ใช่ เราสามารถกำหนดบล็อก 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