본문 바로가기
자바 (JAVA)

📚 JAVA 8강: 예외 처리 (Exception Handling)

by demianpark127 2025. 1. 3.
SMALL

📚 8강: 예외 처리 (Exception Handling)


🚀 1. 예외(Exception)란?

  • **예외(Exception)**는 프로그램 실행 중 발생하는 오류 상황입니다.
  • 예외 처리는 프로그램이 비정상적으로 종료되는 것을 방지하고, 오류 상황에 적절히 대응할 수 있도록 돕습니다.

🚀 2. 예외의 종류

📌 2.1 체크 예외 (Checked Exception)

  • **컴파일 타임(Compile Time)**에 예외 발생 가능성을 검사.
  • 반드시 try-catch 또는 throws를 사용해야 함.

예시:

  • IOException
  • SQLException
import java.io.*;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("nonexistentfile.txt");
        } catch (FileNotFoundException e) {
            System.out.println("파일을 찾을 수 없습니다.");
        }
    }
}

📌 2.2 언체크 예외 (Unchecked Exception)

  • **런타임(Runtime)**에 발생하는 예외.
  • try-catch로 강제하지 않음.
  • 대부분 프로그래머의 실수로 발생.

예시:

  • NullPointerException
  • ArrayIndexOutOfBoundsException
public class UncheckedExceptionExample {
    public static void main(String[] args) {
        String text = null;
        try {
            System.out.println(text.length()); // NullPointerException 발생
        } catch (NullPointerException e) {
            System.out.println("널 포인터 예외 발생");
        }
    }
}

 

📌 2.3 오류 (Error)

  • 심각한 시스템 오류로, 프로그램이 복구할 수 없는 상황.
  • 예: OutOfMemoryError, StackOverflowError

🚀 3. 예외 처리 구조

📌 3.1 try-catch 블록

기본 구조

try {
    // 예외 발생 가능성 있는 코드
} catch (ExceptionType e) {
    // 예외 처리 코드
} finally {
    // 항상 실행되는 코드 (옵션)
}

✅ 예제 코드

public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // ArithmeticException 발생
        } catch (ArithmeticException e) {
            System.out.println("0으로 나눌 수 없습니다.");
        } finally {
            System.out.println("예외 처리 완료.");
        }
    }
}
📌 출력 결과:

0으로 나눌 수 없습니다.
예외 처리 완료.

 

📌 3.2 다중 catch 블록

  • 여러 유형의 예외를 처리할 수 있습니다.
public class MultiCatchExample {
    public static void main(String[] args) {
        try {
            String text = null;
            System.out.println(text.length()); // NullPointerException 발생
            int result = 10 / 0; // ArithmeticException 발생
        } catch (NullPointerException e) {
            System.out.println("널 포인터 예외 발생");
        } catch (ArithmeticException e) {
            System.out.println("0으로 나눌 수 없습니다.");
        } catch (Exception e) {
            System.out.println("알 수 없는 예외 발생");
        }
    }
}

📌 3.3 finally 블록

  • 예외 발생 여부와 상관없이 항상 실행됩니다.
  • 주로 리소스 해제(예: 파일, 네트워크 연결)에 사용됩니다.
public class FinallyExample {
    public static void main(String[] args) {
        try {
            System.out.println("try 블록 실행");
        } catch (Exception e) {
            System.out.println("catch 블록 실행");
        } finally {
            System.out.println("finally 블록 실행");
        }
    }
}
📌 출력 결과:

try 블록 실행
finally 블록 실행

 

🚀 4. 예외 던지기 (throws 키워드)

  • 메서드에서 발생할 수 있는 예외를 호출자에게 전가합니다.
  • 메서드 선언부에 throws를 사용합니다.
import java.io.*;

public class ThrowsExample {
    public static void readFile() throws FileNotFoundException {
        FileReader file = new FileReader("nonexistentfile.txt");
    }

    public static void main(String[] args) {
        try {
            readFile();
        } catch (FileNotFoundException e) {
            System.out.println("파일을 찾을 수 없습니다.");
        }
    }
}

🚀 5. 사용자 정의 예외 (Custom Exception)

  • 사용자 정의 예외는 필요에 따라 새롭게 예외 클래스를 정의할 수 있습니다.
// 사용자 정의 예외 클래스
class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

// 사용자 정의 예외 사용
public class CustomExceptionExample {
    static void checkAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("나이가 18세 미만입니다.");
        }
    }

    public static void main(String[] args) {
        try {
            checkAge(16);
        } catch (InvalidAgeException e) {
            System.out.println(e.getMessage());
        }
    }
}
📌 출력 결과:

나이가 18세 미만입니다.

 

🚀 6. 실습 과제

  1. 예외 처리 실습:
    • 숫자를 입력받아 0으로 나누는 경우 ArithmeticException을 처리하세요.
import java.util.Scanner;

public class ArithmeticExceptionExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.print("숫자를 입력하세요: ");
            int number = scanner.nextInt();

            System.out.print("나눌 숫자를 입력하세요: ");
            int divisor = scanner.nextInt();

            int result = number / divisor; // 0으로 나누면 ArithmeticException 발생
            System.out.println("결과: " + result);

        } catch (ArithmeticException e) {
            System.out.println("오류: 0으로 나눌 수 없습니다.");
        } catch (Exception e) {
            System.out.println("오류: 잘못된 입력입니다.");
        } finally {
            System.out.println("프로그램을 종료합니다.");
            scanner.close();
        }
    }
}

✅ 출력 결과 예시
입력:

숫자를 입력하세요: 10
나눌 숫자를 입력하세요: 0

출력:

오류: 0으로 나눌 수 없습니다.
프로그램을 종료합니다.

 

다중 catch 사용:

  • 배열에서 잘못된 인덱스에 접근하여 ArrayIndexOutOfBoundsException을 처리하세요.
public class ArrayIndexOutOfBoundsExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};

        try {
            System.out.println("배열의 네 번째 요소: " + numbers[3]); // 잘못된 인덱스 접근
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("오류: 배열의 범위를 벗어난 인덱스입니다.");
        } catch (Exception e) {
            System.out.println("오류: 알 수 없는 예외가 발생했습니다.");
        } finally {
            System.out.println("배열 예외 처리를 완료합니다.");
        }
    }
}
✅ 출력 결과 예시
출력:

오류: 배열의 범위를 벗어난 인덱스입니다.
배열 예외 처리를 완료합니다.

 

사용자 정의 예외:

  • 나이가 18세 미만이면 사용자 정의 예외를 발생시키고 처리하세요.
✅ 사용자 정의 예외 클래스 생성

// 사용자 정의 예외 클래스
class UnderAgeException extends Exception {
    public UnderAgeException(String message) {
        super(message);
    }
}

✅ 나이 검사 클래스

import java.util.Scanner;

public class CustomExceptionExample {
    // 나이 검사 메서드
    static void checkAge(int age) throws UnderAgeException {
        if (age < 18) {
            throw new UnderAgeException("오류: 나이가 18세 미만입니다. 접근이 불가능합니다.");
        }
        System.out.println("나이가 적합합니다. 접근이 허용됩니다.");
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.print("나이를 입력하세요: ");
            int age = scanner.nextInt();

            checkAge(age); // 사용자 정의 예외 발생 가능성

        } catch (UnderAgeException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
            System.out.println("오류: 잘못된 입력입니다.");
        } finally {
            System.out.println("나이 검사 완료.");
            scanner.close();
        }
    }
}
✅ 출력 결과 예시
입력:

나이를 입력하세요: 16

출력:

오류: 나이가 18세 미만입니다. 접근이 불가능합니다.
나이 검사 완료.
입력:

나이를 입력하세요: 20
출력:

나이가 적합합니다. 접근이 허용됩니다.
나이 검사 완료.

🎯 7. 학습 목표

  1. 예외의 종류(Checked, Unchecked, Error)를 이해한다.
  2. try-catch-finally를 사용해 예외를 처리할 수 있다.
  3. throws를 사용해 예외를 호출자에게 전가할 수 있다.
  4. 사용자 정의 예외를 생성하고 사용할 수 있다.

다음 강의 예고: 9강 - 컬렉션 프레임워크 (Collection Framework)

다음 강의에서는 자바 컬렉션 프레임워크를 학습합니다. 😊

LIST