티스토리 뷰

Back-end/JAVA

NullPointerException 처리 방법

지나짱-* 2022. 11. 21. 23:07

코드 리뷰를 하면서 값을 비교하는 코드가 있었는데 Equals 함수를 사용하였다. null 값일 경우엔 NullPointerException 이 발생했으며 이에 따른 다양한 처리 방법들을 정리해본다. 

 

1. null객체 대신 리터럴 문자에서 equal 메서드를 호출함으로써 해결할 수 있습니다.

String ptr = null;
if (ptr.equal("abc") { // NullPointerException 발생!
}

if ("abc".equals(ptr)) { // 리터럴문자에서 equal 메소드를 호출
}

2. try - catch문 사용 : 다음과 같이 예외처리 문 사용

public class Main {
 public static void main(String[] arg) {
    String s = null; 
    try { 
     System.out.println(getLength(s)); 
    } 
    catch(IllegalArgumentException e) { 
     System.out.println("IllegalArgumentException caught"); // 예외처리 발생!!
    }
    }
    
    public static int getLength(String s) { 
     if (s == null) {
      throw new IllegalArgumentException("The argument cannot be null");
     } 
     return s.length(); 
    } 
}

3. 삼항 연산자 사용 : null 값은 == 또는!= 의 연산자가 적용하여 사용

public class Main {
 public static void main(String[] arg) {
 	String s = null; 
    System.out.println(s.length()); // NullPointerException 발생!!
  } 
 }


public class Main {
 public static void main(String[] arg) {
 	String s = null; 
    System.out.println((s == null) ? "0" : s.length()); // "0" 출력
  } 
}

4. Optional 사용

Optional의 static method 인 empty(), of(), ofNullable()을 통해서만 Optional 객체를 생성할 수 있다.

참조 변수의 값이 null일 가능성이 있으면, of() 대신 ofNullable()을 사용해야 한다. of()는 매개변수의 값이 null이면 NullPointerException이 발생하기 때문이다.

Optional<String> optVal = Optional.of(null); //NPE 발생
Optional<String> optVal = Optional.ofNullable(null); // OK

5. Objects.equals() 사용

JDK의 Objects.equals() 소스 코드

Objects 클래스의 equals()는 다음과 같이 구현되어있다.

package java.util;

public final class Objects {
  /**
   * Returns {@code true} if the arguments are equal to each other
   * and {@code false} otherwise.
   * Consequently, if both arguments are {@code null}, {@code true}
   * is returned and if exactly one argument is {@code null}, {@code
   * false} is returned.  Otherwise, equality is determined by using
   * the {@link Object#equals equals} method of the first
   * argument.
   *
   * @param a an object
   * @param b an object to be compared with {@code a} for equality
   * @return {@code true} if the arguments are equal to each other
   * and {@code false} otherwise
   * @see Object#equals(Object)
   */
  public static boolean equals(Object a, Object b) {
      return (a == b) || (a != null && a.equals(b));
  }
}

equals()를 호출하는 객체가 null일 가능성이 있기 때문에 null 예외처리를 해야 했다.

equals()로 객체 비교하는 예제

Objects.equals() 다음과 같이 사용할 수 있다.

String aa = null;
String bb = null;
if (Objects.equals(aa, bb)) {
  // ...
}
System.out.println("Objects.equals(null, null): " + Objects.equals(aa, bb));

aa = "google";
bb = "google";
System.out.println("Objects.equals(google, google): " + Objects.equals(aa, bb));

aa= "android";
bb = "google";
System.out.println("Objects.equals(android, google): " + Objects.equals(aa, bb));

결과

Objects.equals(null, null): true
Objects.equals(google, google): true
Objects.equals(android, google): false

null객체 두 개를 비교할 때 Objects.equals는 true를 리턴하기 때문에, 이것이 싫다면 다음과 같이 구현해야 한다.

aa = null;
bb = "google";
if (aa != null && Objects.equals(aa, bb)) {
    System.out.println("non null and eqaul");
} else {
    System.out.println("null or not eqaul");
}

또는 Objects.nonNull()을 사용하여 구현할 수 있다.

aa = null;
bb = "google";
if (Objects.nonNull(aa) && Objects.equals(aa, bb)) {
    System.out.println("non null and eqaul");
} else {
    System.out.println("null or not eqaul");
}

참고로, Objects는 nonNull(), isNull() 메서드들도 지원한다.

public static boolean isNull(Object obj) {
    return obj == null;
}
public static boolean nonNull(Object obj) {
    return obj != null;
}

'Back-end > JAVA' 카테고리의 다른 글

Exception의 종류와 발생원인  (0) 2022.12.12
Optional 활용  (0) 2022.12.11
통합 테스트(Integration Test)  (0) 2022.12.04
로그 사용 - log4j.properties  (0) 2022.11.15
JNI (JAVA Native Interface)  (0) 2022.11.05
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함