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

Try, Catch, Throw, Throws ใน Java - Exception Handling

Try และ Catch ใน Java

Method จับ Exception ด้วยการรวม Keywords try และ catch วาง Try/Catch Block รอบโค้ดที่อาจเกิด Exception

Syntax

try {
    // Protected Code
} catch (ExceptionName e1) {
    // Catch Block
}

Catch Statement ประกาศ Type ของ Exception ที่พยายามจับ หาก Exception เกิดใน Protected Code Catch Block ต่อจาก Try จะถูกตรวจสอบ หาก Type ตรงกัน Exception จะถูกส่งเข้ Catch Block

ตัวอย่าง: Try-Catch กับ ArrayIndexOutOfBoundsException

import java.io.*;

public class Demo {
    public static void main(String[] args) {
        try {
            int a[] = new int[5];
            System.out.println("Access element eighth: " + a[7]);  // Index 7 ไม่มี
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Exception thrown: " + e);
        }
        System.out.println("Out of the block");
    }
}

ผลลัพธ์

Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7
Out of the block

Throw และ Throws ใน Java

  • throws: หาก Method ไม่ Handle Checked Exception ต้องประกาศด้วย throws Keyword อยู่ท้าย Method Signature
  • throw: โยน Exception เอง (New Instance หรือ Exception ที่ Catch มา) ด้วย Keyword throw

ความแตกต่าง:

  • throws - โยนความรับผิดชอบ (Declare) ให้ Caller Handle
  • throw - โยน Exception จริง (Raise) ทันที

ตัวอย่างรวม

public class Demo {
    // ประกาศว่า Method นี้อาจโยน IOException
    public void readFile(String path) throws IOException {
        // โค้ดอ่านไฟล์...
        if (path == null) {
            throw new IllegalArgumentException("Path cannot be null");  // Throw เอง
        }
    }
}

Best Practice: Catch Specific Exception ก่อน General Exception ใช้ Try-with-Resources สำหรับ Auto-Closeable Resources