예외처리

현서·2025년 5월 27일
1

자바

목록 보기
15/32
post-thumbnail

1. 예외처리(Exception Handling)

프로그램 실행 중 발생할 수 있는 오류 상황을 미리 대비하여 프로그램이 비정상적으로 종료되지 않도록 처리하는 방법.

2. 예외 처리 구문

try {
    // 예외가 발생할 수 있는 코드
} catch (ExceptionType e) {
    // 예외 발생 시 처리 코드
} finally {
    // 예외 발생 여부와 무관하게 항상 실행 (선택 사항)
}
package lesson06;

public class Ex01_Main {
    public static void main(String[] args) {
        try{
            int result = 10/0;
            System.out.println("결과: " + result);
        }catch(ArithmeticException e){
            System.out.println("예외 발생: " + e.getMessage());
        }finally{
            System.out.println("이 코드는 항상 실행됩니다.");
        }
    }
}
package lesson06;

public class Ex02_Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        try{
            System.out.println(numbers[3]);
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("배열 범위를 벗어났습니다: " + e);
            System.out.println("배열 범위를 벗어났습니다: " + e.getMessage());
        }
    }
}
package lesson06;

public class Ex03_Main {
    public static void main(String[] args) {
        try{
            String s = null;
            System.out.println(s.length());
        }catch(ArithmeticException e){
            System.out.println("산술 오류: " + e.getMessage());
        } catch (NullPointerException e) {
            System.out.println("널 오류: " + e.getMessage());
        }catch(Exception e){
            System.out.println("기타 오류: " + e.getMessage());
        } // 맨 위에 오면 안 됨. Ctrl + Shift 화살표 위 아래. 코드 왔다갔다 가능.
    }
}
package lesson06;

import java.awt.datatransfer.SystemFlavorMap;
import java.util.Scanner;

public class Ex04_Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try{
            System.out.println("나눗셈 계산기");
            System.out.println("첫 번째 숫자를 입력하세요: ");
            int a = sc.nextInt();
            System.out.println("두 번째 숫자를 입력하세요: ");
            int b = sc.nextInt();

            int result = a / b;
            System.out.println("결과: " + a + "/" + b + " = " + result);
        }catch(ArithmeticException e){
            System.out.println("오류: 0으로 나눌 수 없습니다!");
        }catch(Exception e){
            System.out.println("예기치 못한 오류 발생: " + e.getMessage());
        }finally {
            System.out.println("계산기를 종료합니다. 이용해주셔서 감사합니다.");
            sc.close();
        }
    }
}

3. 예외 던지기

자바에서 예외가 발생한 상황을 직접 명시적으로 알리고 처리 흐름을 넘기는 방법이다.

1. throw 키워드

실제 예외 객체를 생성해서 직접 던질 때 사용한다.

throw new 예외클래스("메시지");

2. throws 키워드

예외를 현재 메서드에서 직접 처리하지 않고, 호출한 쪽으로 넘기겠다고 선언할 때 사용한다.

리턴타입 메서드이름() throws 예외클래스 {
    // 예외 발생 코드
}
package lesson06;

public class Ex05_Main {
    public static double calculateSqrt(int number) throws IllegalArgumentException{
        if(number < 0){
            throw new IllegalArgumentException("음수는 제곱근을 계산할 수 없습니다.");
        }
        return Math.sqrt(number);
    }

    public static void main(String[] args) {
        try{
           // double result = calculateSqrt(-9);
            double result = calculateSqrt(9);
            System.out.println("결과: " + result);
        }catch(IllegalArgumentException e){
            System.out.println("예외 발생: " + e.getMessage());
        }
    }
}

calculateSqrt(int number) 메서드 : throws IllegalArgumentException을 통해 예외를 직접 처리하지 않고 위임한다.

4. 사용자 정의 예외

기존 예외 클래스를 상속받아 개발자가 직접 정의한 예외이다.

1. Checked 사용자 정의 예외 (Exception 상속)

  • 컴파일 시점에 예외 처리(try-catch 또는 throws)가 강제된다.
  • Exception 클래스를 직접 상속받으면 Checked Exception이 된다.
package lesson06;

class InvalidScoreException extends Exception {
    public InvalidScoreException(String message){
        super(message);
    }
}

public class Ex06_Main {
    public static void checkScore(int score) throws InvalidScoreException{
        if(score < 0 || score > 100){
            throw new InvalidScoreException("점수는 0에서 100사이여야 합니다.");
        }
        System.out.println("유효한 점수입니다: " + score);
    }
    public static void main(String[] args) {
        try{
            checkScore(150);
        } catch (InvalidScoreException e){
            System.out.println("예외 처리됨: " + e.getMessage());
        }
    }
}

2. Unchecked 사용자 정의 예외 (RuntimeException 상속)

  • 런타임 시점에 예외가 발생한다.
  • 예외 처리(try-catch 또는 throws)를 강제하지 않는다.
  • RuntimeException 클래스를 상속받으면 Unchecked Exception이 된다.
package lesson06;

class InvalidUserException extends RuntimeException {
    public InvalidUserException(String message) {
        super(message);
    }
}
class UncheckedException{
    public static void validateUsername(String name){
        if(name == null || name.isEmpty()){
            throw new InvalidUserException("사용자 이름은 비어 있을 수 없습니다.");
        }
        System.out.println("사용자 이름: " + name);
    }
}

public class Ex07_Main {
    public static void main(String[] args){
       // UncheckedException ue = new UncheckedException();
        try{
            UncheckedException.validateUsername("");
        }catch (InvalidUserException e){
            System.out.println("예외 처리됨: " + e.getMessage());
        }
    }
}
항목Checked 예외Unchecked 예외
상속ExceptionRuntimeException
예외 처리 강제 여부강제됨강제되지 않음
대표 예IOException, SQLExceptionNullPointerException, ArrayIndexOutOfBoundsException
사용자 정의 시extends Exceptionextends RuntimeException
  • Checked 예외 : 외부 자원(I/O, DB 등)에서 문제가 생길 가능성이 있을 때 명시적으로 처리 유도.

  • Unchecked 예외 : 개발자가 잘못된 호출이나 비정상적인 사용에 대한 버그를 나타낼 때 사용.

profile
The light shines in the darkness.

0개의 댓글