자바의 정석 - 사용자정의예외 만들기, 예외 되던지기

Yohan·2024년 2월 1일
0

사용자정의 예외 만들기

  • 우리가 직접 예외 클래스를 정의할 수 있다.
  • 조상은 Exception과 RuntimeException중에서 선택
    • unchecked 예외인 RuntimeException가 예외 처리가 필수적이지 않으므로 권장.
class MyException extends Exception {
	MyException(String msg) { // 문자열을 매개변수로 받는 생성자
    	super(msg); // 조상인 Exception클래스의 생성자를 호출
    }
}

예외 되던지기

  • 예외를 처리한 후에 다시 예외를 발생시키는 것
  • 호출한 메서드와 호출된 메서드 양쪽 모두에서 예외처리하는 것
public class Ex1 {
	public static void main(String[] args) {
	try {
		method1();
	} catch (Exception e){
		System.out.println("main메서드에서 예외가 처리되었습니다.");
	}
	
}
	static void method1() throws Exception {
		try {
			throw new Exception();
		} catch(Exception e) {
			System.out.println("method1메서드에서 예외가 처리되었습니다.");
			throw e; // 다시 예외 발생
		}
		
	}
}
// 출력

// method1메서드에서 예외가 처리되었습니다.
// main메서드에서 예외가 처리되었습니다.

예외처리 3가지 방법

  1. 예외가 발생한 곳에서 try-catch문으로 직접 처리
  2. 예외를 호출한 쪽에서 처리 (예외 떠넘기기)
  3. 양쪽에서 처리 (예외 되던지기, 분담처리)
profile
백엔드 개발자

0개의 댓글