책/멘토씨리즈 자바

[멘토씨리즈 자바] 14 예외 처리 응용문제

yn98 2024. 7. 29. 17:17

1. 다음 코드는 컴파일 오류가 발생합니다. 오류를 확인하고 예외 처리 문법을 사용하여 해결해보세요.

public class valueExceptionExample {
	public static void main(String[] args) {
    	int data = 10;
        double result = 0;
        
        result = (double)data / 0;
        
        System.out.println("결과는 : " + result);
    }
}

 

0으로는 나눌 수 없다. ( ArithmeticException e)


public class ValueExceptionExample {
	public static void main(String[] args) {
		int data = 10;
		double result = 0;

		try {
			// 0으로 나누는 연산은 예외를 발생시킬 수 있으므로 try 블록에 포함
			result = (double) data / 0;
		} catch (ArithmeticException e) {
			// 예외가 발생했을 때 실행되는 블록
			System.out.println("예외 발생: " + e.getMessage());
		} finally {

			// 예외가 발생하더라도 결과를 출력
			System.out.println("결과는 : " + result);
		}
	}
}

 

 

2. 다음 코드에서 사용자가 음수를 입력할 경우 임의로 예외를 발생시켜 음수의 값을 합산에 포함되지 않도록 처리해 보세요.

 

import java.util.Scanner;
public class MinusValueExceptionExample {
	public static void main(String[] args) {
    	Scanner scan = new Scanner(System.in);
        int count = 5;
        int data = 0;
        int sum = 0;
        while(count < 5) {
        	System.out.println("숫자를 입력하세요:");
            data = scan.nextInt();
            sum += data;
        }
        System.out.println("숫자 합 : " + sum);
    }
}

 

NegativeValueException이라는 사용자 정의 예외 클래스를 만들어서 해결했다.

import java.util.Scanner;

public class MinusValueExceptionExample {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int count = 0; // 5개의 숫자를 입력받기 위한 카운트
        int data = 0;
        int sum = 0;

        while (count < 5) {
            System.out.println("숫자를 입력하세요:");
            try {
                data = scan.nextInt();
                
                // 음수 값이 입력된 경우 예외 발생
                if (data < 0) {
                    throw new NegativeValueException("음수는 입력할 수 없습니다. 입력된 값: " + data);
                }
                
                sum += data;
                count++;
            } catch (NegativeValueException e) {
                // 음수가 입력된 경우 예외 메시지를 출력하고 다시 입력 받기
                System.out.println(e.getMessage());
            }
        }
        
        System.out.println("숫자 합 : " + sum);
        scan.close(); // Scanner 객체 닫기
    }
}


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