Programming/Java의 정석

[Javad의 정석 3판] chapter8 예외처리

yndev 2022. 1. 21. 23:06

[8-1] 예외처리의 정의와 목적에 대해서 설명하시오.

정의 : 프로그램 실행 시 발생할 수 있는 예외의 발생에 대비한 코드를 작성하는 것

목적 : 프로그램의 비정상 종료를 막고, 정상적인 실행상태를 유지하는 것

 

[8-2] 다음은 실행도중 예외가 발생하여 화면에 출력된 내용이다. 이에 대한 설명 중 옳
지 않은 것은?

답 : d (d는 무조건 옳은 설명인 줄 알았다. 당연한걸 문제로 접하면 헷갈림)

 

[8-3] 다음 중 오버라이딩이 잘못된 것은? (모두 고르시오)

답 : d, e

오버라이딩할 때 조상클래스의 메소드보다 많은 수의 예외를 선언할 수 없다.

Exception은 모든 예외의 조상클래스이므로 개수가 적어보여도 제일 많은 개수를 가지고 있다.

 

[8-4] 다음과 같은 메서드가 있을 때, 예외를 잘못 처리한 것은? (모두 고르시오)

답 : c

Exception은 제일 마지막에 있어야 함.

 

[8-5] 아래의 코드가 수행되었을 때의 실행결과를 적으시오.

class Exercise8_5 {
	static void method(boolean b) {
		try {
			System.out.println(1);
			if(b) throw new ArithmeticException();
			System.out.println(2);
		} catch(RuntimeException r) {
			System.out.println(3);
			return;
		} catch(Exception e) {
			System.out.println(4);
			return;
		} finally {
			System.out.println(5);
		}
		System.out.println(6);
}

public static void main(String[] args) {
	method(true);
	method(false);
	} // main
}

답 : 예외발생 - 1 3 5 6 (중간에 개행되어야 함)

      예외발생X - 1 2 5 6 

 

[8-6] 아래의 코드가 수행되었을 때의 실행결과를 적으시오.

class Exercise8_6 {
	public static void main(String[] args) {
		try {
			method1();
		} catch(Exception e) {
			System.out.println(5);
		}
	}
	static void method1() {
		try {
			method2();
			System.out.println(1);
		} catch(ArithmeticException e) {
			System.out.println(2);
		} finally {
			System.out.println(3);
		}
		
        System.out.println(4);
	} // method1()

	static void method2() {
		throw new NullPointerException();
	}
}

답 : 

3

5

(메소드2 에서는 try-catch 구문이 없어서 종료되고 메소드1로 넘어가는데

메소드1에서도 NullpointerException을 처리할 구문이 없어서 메소드1의 finally 수행 후(3) 종료되고 main으로 넘어감. main에서 Exception이 존재해서 여기서 예외처리 후 출력(5))

 

[8-7] 아래의 코드가 수행되었을 때의 실행결과를 적으시오.

class Exercise8_7 {
	static void method(boolean b) {
		try {
			System.out.println(1);
			if(b) System.exit(0);
			System.out.println(2);
		} catch(RuntimeException r) {
			System.out.println(3);
			return;
		} catch(Exception e) {
			System.out.println(4);
			return;
		} finally {
			System.out.println(5);
		}
		System.out.println(6);
	}

	public static void main(String[] args) {
		method(true);
		method(false);
	} //main
}

답 : 1

(변수 b의 값이 true이므로 System.exit(0); 이 수행되어 프로그램 즉시 종료됨. 이 때 finally블럭이 수행되지 않는다.)

 

[8-8] 다음은 1~100사이의 숫자를 맞추는 게임을 실행하던 도중에 숫자가 아닌 영문자를 넣어서 발생한 예외이다. 예외처리를 해서 숫자가 아닌 값을 입력했을 때는 다시 입력을 받도록 보완하라.

import java.util.*;

class Exercise8_8
{
	public static void main(String[] args)
	{
		// 1~100사이의 임의의 값을 얻어서 answer에 저장한다.
		int answer = (int)(Math.random() * 100) + 1;
		int input = 0; // 사용자입력을 저장할 공간
		int count = 0; // 시도횟수를 세기 위한 변수
		
        	do {
			count++;
			System.out.print("1과 100사이의 값을 입력하세요 :");

			input = new Scanner(System.in).nextInt();

			if(answer > input) {
				System.out.println("더 큰 수를 입력하세요.");
			} else if(answer < input) {
				System.out.println("더 작은 수를 입력하세요.");
			} else {
				System.out.println("맞췄습니다.");
				System.out.println("시도횟수는 "+count+"번입니다.");
				break; // do-while문을 벗어난다
			}
		} while(true); // 무한반복문
	} // end of main
} // end of class HighLow

 

[8-9] 다음과 같은 조건의 예외클래스를 작성하고 테스트하시오.
[참고] 생성자는 실행결과를 보고 알맞게 작성해야한다.

class Exercise8_9
{
	public static void main(String[] args) throws Exception
	{
		throw new UnsupportedFuctionException("지원하지 않는 기능입니다.",100);
	}
}

=>

class UnsupportedFunctionException extends RuntimeException{
	private final int ERR_CODE;
	
	UnsupportedFunctionException(String msg, int errCode){
		super(msg);
		ERR_CODE = errCode;
	}
	UnsupportedFunctionException(String msg){
		this(msg,100);
	}
	
	public int getErrCode() {
		return ERR_CODE;
	}
	public String getMessage() {
		return "["+getErrCode()+"]" + super.getMessage();
	}
}
class Exercise8_9
{
	public static void main(String[] args) throws Exception
	{
		throw new UnsupportedFunctionException("지원하지 않는 기능입니다.",100);
	}
}

어렵다..흑흑

 

[8-10] 아래의 코드가 수행되었을 때의 실행결과를 적으시오.

class Exercise8_10 {
	public static void main(String[] args) {
		try {
			method1();
			System.out.println(6);
		} catch(Exception e) {
			System.out.println(7);
		}
	}

	static void method1() throws Exception {
		try {
			method2();
			System.out.println(1);
		} catch(NullPointerException e) {
			System.out.println(2);
			throw e;
		} catch(Exception e) {
			System.out.println(3);
		} finally {
			System.out.println(4);
		}

		System.out.println(5);
	} // method1()
	
    static void method2() {
		throw new NullPointerException();
	}
}