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

วิธีแก้ไข NullPointerException ใน Java

NullPointerException เป็น runtime exception ที่ JVM โยนเมื่อ application code, referenced API อื่นๆ หรือ middleware พบเงื่อนไขต่อไปนี้:

  • พยายาม invoke instance method ของ null object
  • พยายาม access หรือ modify field เฉพาะของ null object
  • พยายาม get length ของ null object ในรูป array

ขั้นตอนแก้ไข NullPointerException:

  • Review java.lang.NullPointerException stack trace และกำหนดว่า Exception ถูก trigger ที่ไหน (Application code, third-party API, middleware software และดึง line number)
  • ถ้าปัญหาอยู่ที่ application code จะต้อง code walk-through ถ้าปัญหาจาก third-party API หรือ middleware ต้อง review referenced code ก่อน และกำหนดว่าอาจเป็น indirect source เช่น ส่ง null value ไป third party API method ฯลฯ
  • ถ้าพบปัญหาใน application code พยายามกำหนดว่า Object instance ไหนเป็น null และก่อให้เกิดปัญหา ต้องแก้โค้ดเพื่อเพิ่ม null check validations ที่เหมาะสม และ proper logging เพื่อเข้าใจ source ของ null value

ตัวอย่าง

public class NPEDemo {
    private String field1 = null;
    private String field2 = null;
    public String getField1() {
        return field1;
    }
    private void setField1(String field1) {
        this.field1 = field1;
    }
    public String getField2() {
        return field2;
    }
    private void setField2(String field2) {
        this.field2 = field2;
    }
    public static void main(String[] args) {
        try {
            NPEDemo npe = new NPEDemo();
            npe.setField1("field1 value");
            npe = null;
            npe.setField2("field2 Value");
        } catch (Throwable e) {
            System.out.println("Java Error is: "+e );
            e.printStackTrace();
        }
    }
}

ผลลัพธ์

Java Error is: java.lang.NullPointerException
java.lang.NullPointerException
    at NPEDemo.main(NPEDemo.java:24)