∮explotación≒ 개발

Java에서 빈번히 발생하는 오류 유형 10가지 및 해결 방법

TipoAzul 2025. 6. 23.
반응형

 

 

 

Java 오류 제거 절차

Java 오류 제거 절차오류 메시지 분석입력한 코드: import java.util.Scanner; public class SumNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter first number:"); int num1 = s

tipoazul.tistory.com

 

 

 

 

Java에서 빈번히 발생하는 오류 유형 10가지 및 해결 방법

Java에서 빈번히 발생하는 오류 유형 10가지 및 해결 방법

NullPointerException

객체가 null일 때 메서드나 속성에 접근하려고 할 때 발생합니다.

예시:
          String str = null;
          int length = str.length(); // NullPointerException 발생
        
해결 방법:

객체가 null인지 확인 후 메서드를 호출하거나, 객체를 생성한 후 사용합니다.

          if (str != null) {
              int length = str.length();
          } else {
              System.out.println("String is null");
          }
        

ArrayIndexOutOfBoundsException

배열의 잘못된 인덱스를 참조할 때 발생합니다.

예시:
          int[] arr = {1, 2, 3};
          int value = arr[3]; // ArrayIndexOutOfBoundsException 발생
        
해결 방법:

배열의 유효한 인덱스를 참조하고 있는지 확인합니다.

          if (index >= 0 && index < arr.length) {
              int value = arr[index];
          } else {
              System.out.println("Invalid array index");
          }
        

ClassCastException

객체를 잘못된 타입으로 캐스팅할 때 발생합니다.

예시:
          Object obj = "Hello";
          Integer num = (Integer) obj; // ClassCastException 발생
        
해결 방법:

캐스팅을 하기 전에 instanceof 연산자를 사용하여 타입을 확인합니다.

          if (obj instanceof Integer) {
              Integer num = (Integer) obj;
          } else {
              System.out.println("Invalid type for casting");
          }
        

ArithmeticException

0으로 나누기 등의 수학적 오류가 발생할 때 발생합니다.

예시:
          int result = 10 / 0; // ArithmeticException 발생
        
해결 방법:

나누기 전에 0으로 나누지 않는지 확인합니다.

          if (denominator != 0) {
              int result = numerator / denominator;
          } else {
              System.out.println("Cannot divide by zero");
          }
        

NumberFormatException

문자열을 숫자로 변환할 때 형식이 맞지 않으면 발생합니다.

예시:
          String str = "abc";
          int num = Integer.parseInt(str); // NumberFormatException 발생
        
해결 방법:

문자열이 숫자 형식인지를 미리 확인하거나, 예외 처리를 사용합니다.

          try {
              int num = Integer.parseInt(str);
          } catch (NumberFormatException e) {
              System.out.println("Invalid number format");
          }
        

FileNotFoundException

지정된 파일을 찾을 수 없을 때 발생합니다.

예시:
          File file = new File("nonexistent.txt");
          Scanner sc = new Scanner(file); // FileNotFoundException 발생
        
해결 방법:

파일이 존재하는지 확인하거나, 파일 경로를 올바르게 설정합니다.

          File file = new File("existing_file.txt");
          if (file.exists()) {
              Scanner sc = new Scanner(file);
          } else {
              System.out.println("File not found");
          }
        

IllegalArgumentException

메서드에 부적절한 인자를 전달할 때 발생합니다.

예시:
          Thread.sleep(-1000); // IllegalArgumentException 발생
        
해결 방법:

메서드에 적절한 인자를 전달하도록 합니다.

          if (time >= 0) {
              Thread.sleep(time);
          } else {
              System.out.println("Invalid argument for sleep time");
          }
        

NoSuchElementException

Scanner로 입력을 받을 때 더 이상 입력할 내용이 없을 때 발생합니다.

예시:
          Scanner sc = new Scanner(System.in);
          sc.nextInt(); // 입력이 없으면 NoSuchElementException 발생
        
해결 방법:

입력을 받기 전에 입력이 존재하는지 확인하거나, 예외 처리를 합니다.

          if (sc.hasNextInt()) {
              int num = sc.nextInt();
          } else {
              System.out.println("No valid input");
          }
        

ConcurrentModificationException

컬렉션을 순회하는 동안 그 컬렉션을 수정하면 발생합니다.

예시:
          List list = new ArrayList<>();
          list.add("A");
          list.add("B");

          for (String item : list) {
              list.remove(item); // ConcurrentModificationException 발생
          }
        
해결 방법:

순회 중 컬렉션을 수정하지 않거나, Iterator를 사용하여 안전하게 수정합니다.

          Iterator iterator = list.iterator();
          while (iterator.hasNext()) {
              String item = iterator.next();
              iterator.remove();
          }
        

StackOverflowError

재귀 함수가 종료 조건 없이 계속 호출될 때 발생합니다.

예시:
          public class Recursion {
              public void recurse() {
                  recurse(); // StackOverflowError 발생
              }
          }
        
해결 방법:

재귀 함수에 종료 조건을 추가하여 무한 재귀를 방지합니다.

          public void recurse(int n) {
              if (n == 0) return; // 종료 조건
              recurse(n - 1);
          }
        
반응형

'∮explotación≒ 개발' 카테고리의 다른 글

Java 오류 제거 절차  (3) 2025.06.23
oracle REGEXP_SUBSTR 예제  (0) 2023.05.01
InternalError: too much recursion  (0) 2023.04.23
Error: Permission denied to access property  (0) 2023.04.23
JavaScript 상속과 프로토타입  (0) 2023.04.17

댓글