Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

자바 NumberFormatException(비검사 예외) 발생 원인과 처리 방법 총정리

NumberFormatException비검사 예외(unchecked exception)의 하나로, parseXXX() 메서드가 문자열을 숫자로 변환(format)하지 못할 때 발생합니다.

이 예외는 java.lang 패키지에 속한 여러 클래스의 메서드나 생성자에 의해 던져질 수 있습니다. 대표적인 메서드들은 다음과 같습니다.

  • public static int parseInt(String s) throws NumberFormatException
  • public static Byte valueOf(String s) throws NumberFormatException
  • public static byte parseByte(String s) throws NumberFormatException
  • public static byte parseByte(String s, int radix) throws NumberFormatException
  • public Integer(String s) throws NumberFormatException
  • public Byte(String s) throws NumberFormatException

각 메서드마다 NumberFormatException이 발생하는 조건이 정의되어 있습니다. 예를 들어 public static int parseInt(String s) 메서드는 다음과 같은 경우에 예외를 던집니다.

  • 문자열 s가 null이거나 길이가 0일 때
  • 문자열 s에 숫자가 아닌 문자가 포함되어 있을 때
  • 문자열 s의 값이 Integer 범위를 나타내지 못할 때

예제 1: NumberFormatException 발생 상황

public class NumberFormatExceptionTest {
    public static void main(String[] args){
        int x = Integer.parseInt("30k");
        System.out.println(x);
    }
}

실행 결과

Exception in thread "main" java.lang.NumberFormatException: For input string: "30k"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:580)
        at java.lang.Integer.parseInt(Integer.java:615)
        at NumberFormatExceptionTest.main(NumberFormatExceptionTest.java:3)

위 예제에서 Integer.parseInt("30k")는 숫자가 아닌 문자 'k'가 포함된 문자열을 정수로 변환하려고 시도하기 때문에 NumberFormatException이 발생합니다.

NumberFormatException 처리 방법

NumberFormatException은 크게 두 가지 방법으로 처리할 수 있습니다.

  • try-catch 블록 사용: NumberFormatException이 발생할 가능성이 있는 코드를 try 블록으로 감싸고, catch 블록에서 예외를 처리합니다.
  • throws 키워드 사용: 메서드 선언부에 throws 키워드를 명시하여 예외를 호출한 메서드로 전달합니다.

예제 2: try-catch와 throws를 활용한 예외 처리

public class NumberFormatExceptionHandlingTest {
    public static void main(String[] args) {
        try {
            new NumberFormatExceptionHandlingTest().intParsingMethod();
        } catch (NumberFormatException e) {
            System.out.println("We can catch the NumberFormatException");
        }
    }
    public void intParsingMethod() throws NumberFormatException{
        int x = Integer.parseInt("30k");
        System.out.println(x);
    }
}

위 예제에서 intParsingMethod() 메서드는 Integer.parseInt("30k")에서 발생한 예외 객체를 자신을 호출한 메서드, 즉 이 경우에는 main() 메서드로 던집니다. 그리고 main() 메서드의 catch 블록이 해당 예외를 받아 처리하게 됩니다.

실행 결과

We can catch the NumberFormatException

이처럼 비검사 예외인 NumberFormatException도 컴파일러가 강제하지는 않지만, 프로그램의 안정성을 위해 적절히 처리해 주는 것이 좋습니다.