Java 예외 처리 및 메소드 활용

프로젝트 구조

5.3 예외 처리 문법

예제: ExceptionTest01

catch 블록에서 return 문을 실행하더라도 finally 블록의 코드는 반드시 실행된다. 따라서 "캡처된 예외 정보: / by zero"가 출력된 후 "finally 코드 블록 진입" 메시지가 출력된다.

코드 예시

package com.example.exception;

/**
 * 핵심 포인트:
 * 1. finally 블록의 역할: 예외 발생 여부와 관계없이 finally 블록 내의 코드가 항상 실행됨
 */
public class ExceptionTest01 {
    public static void main(String[] args) {
        // try-catch-finally 구조를 사용하여 예외를 처리
        try {
            int quotient = calculate(10, 0);  // calculate() 메소드 호출
            System.out.println("연산 결과: " + quotient);
        } catch (ArithmeticException e) {     // 캡처된 예외 처리
            System.out.println("예외 메시지: " + e.getMessage());
            return;                            // 현재 메소드 종료
        } finally {
            System.out.println("finally 코드 블록 진입");
        }
        System.out.println("프로그램 계속 실행...");
    }

    // 두 정수를 나누는 메소드
    public static int calculate(int a, int b) {
        int quotient = a / b;      // 두 수의 나눗셈 결과를 저장
        return quotient;           // 결과 반환
    }
}

실행 결과

5.4 예외 던지기

예제: ExceptionTest02

이 코드는 throws Exception을 사용하여 메소드가 예외를 발생시킬 수 있음을 선언한다. 호출 시 try-catch 블록으로 ArithmeticException을 처리하고, printStackTrace()를 통해 예외 스택 정보를 출력한다.

코드 예시

package com.example.exception;

/**
 * 핵심 포인트:
 * 1. throws 키워드를 사용하여 메소드에서 예외 발생 선언 가능
 * 2. 호출자는 해당 메소드 호출 시 예외를 처리하거나 계속 던져야 함
 */
public class ExceptionTest02 {
    public static void main(String[] args) {
        // try-catch 문을 사용하여 예외 처리
        try {
            int value = compute(20, 0);  // compute() 메소드 호출
            System.out.println("연산 결과: " + value);
        } catch (Exception e) {          // 캡처된 예외 처리
            e.printStackTrace();         // 예외 스택 정보 출력
        }
    }

    // 두 정수를 나누는 메소드, throws로 예외 던지기 선언
    public static int compute(int num1, int num2) throws Exception {
        int value = num1 / num2;     // 나눗셈 결과 저장
        return value;                // 결과 반환
    }
}

실행 결과

예제: ExceptionTest03

main 메소드에서 throws Exception을 사용하여 divideNumbers 메소드의 예외를 상위 호출 환경(JVM)으로 계속 던진다. 이로 인해 프로그램이 종료되고 예외 스택 정보가 출력된다.

코드 예시

package com.example.exception;

/**
 * 핵심 포인트:
 * 1. 호출한 메소드의 예외 처리 방법을 모르는 경우, throws 키워드를 사용하여 예외를 계속 던질 수 있음
 */
public class ExceptionTest03 {
    public static void main(String[] args) throws Exception {
        int result = divideNumbers(15, 0);  // divideNumbers() 메소드 호출
        System.out.println("나눗셈 결과: " + result);
    }

    // 두 정수를 나누는 메소드, throws로 예외 던지기 선언
    public static int divideNumbers(int num1, int num2) throws Exception {
        int result = num1 / num2;     // 나눗셈 결과 저장
        return result;                // 결과 반환
    }
}

실행 결과

5.5 사용자 정의 예외

예제: CustomExceptionDemo

이 코드는 NegativeDivisorException이라는 사용자 정의 예외를 정의한다.除数为负数일 때 이 예외를 발생시키고, main 메소드에서 try-catch로 캡처하여 예외 정보를 출력한다.

코드 예시

package com.example.exception;


/**
 * 핵심 포인트:
 * 1. 사용자 정의 예외 클래스: 프로그램 요구사항에 따라 사용자가 직접 정의하는 예외 클래스
 * 2. 사용자 정의 예외 클래스는 Exception 클래스 또는 그 하위 클래스를 상속해야 함
 */
class NegativeDivisorException extends Exception {
    public NegativeDivisorException() {
        super();                           // Exception 기본 생성자 호출
    }

    public NegativeDivisorException(String msg) {
        super(msg);                        // Exception 매개변수 생성자 호출
    }
}

public class CustomExceptionDemo {
    public static void main(String[] args) {
        // try-catch 문을 사용하여 예외 처리
        try {
            int result = divideNumbers(8, -3);
            System.out.println("연산 결과: " + result);
        } catch (NegativeDivisorException e) {   // 캡처된 예외 처리
            System.out.println("예외 정보: " + e.getMessage());
        }
    }

    // 두 정수를 나누는 메소드, 사용자 정의 예외 던지기 선언
    public static int divideNumbers(int num1, int num2) throws NegativeDivisorException {
        if (num2 < 0) {
            throw new NegativeDivisorException("나누는 수가 음수입니다");
        }
        int result = num1 / num2;     // 나눗셈 결과 저장
        return result;                // 결과 반환
    }
}

실행 결과

태그: java Exception-Handling throws try-catch-finally custom-exception

6월 17일 04:53에 게시됨