8장 - 예외처리

·2022년 12월 19일
1

자바의 정석

목록 보기
11/12
post-thumbnail

예외 처리

1. try-catch

발생한 예외. 내가 직접 조진다

try블럭 안에 예외 발생 가능성 문장을 넣고, catch 안에 발생 시 처리할 문장을 넣으믄 됨.

class ExceptionEx1 {
	public static void main(String[] args) {
    	System.out.println(1);
        System.out.println(2);
        try {
        	System.out.println(3);
            System.out.println(0/0); // 예외 발생
            System.out.println(4);
        } catch (ArithmeticException ae) {
        	System.out.println("오류당");
        } catch (Exception e) {
        	System.out.println("실행 안되자너");
        }
    }
}

//멀티 catch 예시

class test {
	try {
    		...
    } catch (ExceptionA | ExceptionB) {
    	if ( e instanceof ExceptionA) {
        	ExceptionA e1 = (ExceptionA) e;
            e1.methodA();
        } else {
        	...
        }
    }
}

2. 일부러 예외 발생 시키기

  1. new를 이용해 발생시키려는 예외 클래스 객체 생성
    Exception e = new Exception("고의다");
  2. throw를 이용해 예외 발생
    throw e;
class ExceptionEx0 {
	public static void main(String[] args) {
    	try {
        	throw new Exception("고의맨");
        } catch (Exception e) {
        	Systm.out.println("에러 메세지 : " + e.getMessage());
            e.printStackTrace();
        }
    }
}

3. 메서드에 예외 선언

나 말고 나 부른넘이 처리해 줄겁니다..
메서드 호출 시 어떤 예외가 발생할 수 있다고 미리 알리기

+) 예외 되던지기

4. finally

이새기 점점 대충쓰는거같은데 아닙니다 아니애요 나애대한 공격을멈처줘요

예외 발생 여부에 상관없이 실행되도록. try블럭 안에 return문이 있어서 try블럭을 벗어나야 할 때도 finally블럭은 실행된다.

예시는 깃허브를 보세요

5. 연결된 예외

  1. 여러 예외를 하나로 묶어서 다루기 위해
  2. checked 예외 -> unchecked 예외로 변경 시
Throwable initCause(Throwable cause) //지정한 예외를 원인예외로 등록
Throwable getCause() // 원인 예외를 반환
static void startInstall() throws SpaceException, MemoryException {
	if (!enoughSpace())
    	throw new SpaceException("설치할 공간 부족");
    if (!enoughMemory())
    	throw new MemoryException("메모리 부족");
}
아래와 같이 고쳐보자

static void startinstall() throw SpaceException {
	if (!enoughSpace())
    	throw new SpaceException("설치할 공간 부족");
    if (!enoughMemory())
    	throw new RuntimeException(new MemoryException("메모리 부족"));
}

checked 예외인 MemoryException을 RuntimeException으로 감싸 unchecked 예외로 전환시켰다.

profile
어?머지?

2개의 댓글

comment-user-thumbnail
2022년 12월 21일

진짜 돌아버린 사람이 쓴 글 같아요
재밌게 잘 보고갑니다 !

1개의 답글