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

ประกาศ Try-Catch ซ้อนกัน (Nested) ใน Java ได้ไหม?

ได้ สามารถประกาศ Try-Catch Block ภายใน Try-Catch Block อื่น เรียกว่า Nested Try-Catch Block

การทำงานของ Nested Try-Catch

  • Inner Try Block รันก่อน Exception ใน Inner จะถูกจับโดย Inner Catch ก่อน
  • ถ้า Inner Catch ไม่จับ Exception นั้น (ไม่ Match) จะขึ้นไปที่ Outer Catch
  • ดำเนินต่อจนกว่า Catch Match หรือ หมด Nested Try
  • ถ้าไม่มี Match ใดๆ Java Runtime จัดการ (Print Stack Trace, Terminate Thread)

ไวยากรณ์


try {
    statement 1;
    statement 2;
    try {          // Inner Try
        statement 1;
        statement 2;
    } catch (Exception e) {  // Inner Catch
        // Handle
    }
} catch (Exception e) {  // Outer Catch
    // Handle
}

ตัวอย่างโค้ด


import java.io.*;

public class NestedTryCatchTest {
    public static void main(String args[]) throws IOException {
        int n = 10, result = 0;
        
        try {  // Outer Try
            FileInputStream fis = null;
            fis = new FileInputStream(new File(args[0]));
            
            try {  // Inner Try
                result = n / 0;  // ArithmeticException
                System.out.println("Result: " + result);
            } catch (ArithmeticException e) {  // Inner Catch
                System.out.println("Division by Zero");
            }
        } catch (FileNotFoundException e) {  // Outer Catch
            System.out.println("File was not found");
        } catch (ArrayIndexOutOfBoundsException e) {  // Outer Catch
            System.out.println("Array Index Out Of Bounds Exception occurred");
        } catch (Exception e) {  // Outer Catch (Generic)
            System.out.println("Exception occurred: " + e);
        }
    }
}

ผลลัพธ์


Array Index Out Of Bounds Exception occurred

คำอธิบาย: args[0] ไม่มี → ArrayIndexOutOfBoundsException ใน Outer Try → จับได้ที่ Outer Catch

เมื่อไหร่ควรใช้ Nested Try-Catch?

  • Resource Acquisition ที่อาจ Fail (Outer) + Business Logic ที่อาจ Fail (Inner)
  • JDBC: Outer Try จัดการ Connection, Inner Try จัดการ Statement/ResultSet
  • แยก Error Handling ระดับต่างๆ (Resource vs Logic)

แนวทางสมัยใหม่: Try-With-Resources (Java 7+)

แทน Nested Try-Catch สำหรับ Resource Management:


// แทน Nested Try-Catch สำหรับ Close Resources
try (Connection con = DriverManager.getConnection(url);
     Statement stmt = con.createStatement();
     ResultSet rs = stmt.executeQuery(sql)) {
    // Use resources
} catch (SQLException e) {
    // Handle
}
// ทั้ง 3 ปิดอัตโนมัติ ไม่ต้อง Nested Try-Catch-Finally

ข้อควรระวัง

  • Nested มากเกินไป → Code ซับซ้อน ยากอ่าน (Arrow Code)
  • Catch Exception แบบ Generic (Exception e) ควรอยู่ Outer Most
  • Inner Catch ควร Specific (ArithmeticException, NullPointerException)