정리/Java

자바의 정석 연습문제 ch 8 예외처리

민발자 2023. 8. 31. 20:02
728x90

자바의 정석 3판 기초판 연습문제

https://github.com/castello/javajungsuk3

 

GitHub - castello/javajungsuk3: soure codes and ppt files of javajungsuk 3rd edition

soure codes and ppt files of javajungsuk 3rd edition - GitHub - castello/javajungsuk3: soure codes and ppt files of javajungsuk 3rd edition

github.com

 

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

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

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

→ 에러와 예외

에러 : 프로그램 코드에 의해 수습될 수 없는 심각한 오류

예외 : 프로그램 코드에 의해 수습될 수 있는 미약한 오류

 

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

java.lang.ArithmeticException : / by zero
	at ExceptionEx18.method2(ExceptionEx18.java:12)
	at ExceptionEx18.method1(ExceptionEx18.java:8)
	at ExceptionEx18.main(ExceptionEx18.java:4)

a. 위의 내용으로 예외가 발생했을 당시 호출스택에 존재했던 메서드를 알 수 있다.

b. 예외가 발생한 위치는 method2 메서드이며, ExceptionEx18.java파일의 12번째 줄이다.

c. 발생한 예외는 ArithmethicException이며, 0으로 나누어서 예외가 발생했다.

d. method2 메서드가 method1메서드를 호출하였고 그 위치는 ExceptionEx18.java 파일의 8번째 줄이다.

mehtod1이 mrthod2를 호출

 

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

void add(int a, int b) throws InvalidNumberException, NotNumberException {}
	
class NumberException extends Exception {}
class InvalidNumberException extends NumberException {}
class NotNumberException extends NumberException {}

 

a. void add(int a, int b) throws InvalidNumberException, NotANumberException {}

b. void add(int a, int b) throws InvalidNumberException {}

c. void add(int a, int b) throws NotANumberException {}

d. void add(int a, int b) throws Exception {}

e. void add(int a, int b) throws NumberException {}

오버라이딩할 때 조상보다 더 많은 수의 예외를 선언할 수 없다.

 

[8-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);
}

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

main method1() method2() NullpointException 발생 method2() 종료 method1() 예외 처리못하고 finally 실행 3 출력 method1() 종료 main 모든 예외 처리 catch 5 출력

→ 결과

3

5

 

[8-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);
}

변수 b 값이 true로  System.exit(0); 실행되어 바로 프로그램 종료, finally블럭도 수행되지 않고 종료된다.

→ 실행 결과

1

728x90