Fast Blinking Hello Kitty
 

[📖JAVA] 자바 예외 처리 try-catch-finally 이해하기➰(throw throws)

예외가 발생하면 프로그램을 중단하고 오류 메시지를 보여줍니다. 만약 이 경우에 예외 처리를 해준다면, 프로그램 중단없이 오류 메시지를 출력하고 다음 프로세스로 넘어가도록 조치해줍니다.

1️⃣ 예외 종류

자바에서 정의하는 예외 처리 오류

▪️ Checked Exception
명시적으로 예외처리를 강제화 O (컴파일러가 알려줌)

▪️ Unchecked Exception
명시적으로 예외처리를 강제화 X

👉🏻 예외 처리를 확인/비확인하는 차이
두 가지 예외는 모두 예외 처리가 필요

2️⃣ try-catch 문
예외처리를 하기 위해 사용하는 구문입니다.

public class DivideExceptionSample { 
	public static void main(String[] args) {
		int result;
		try {
			result = 5 / 0;
		} catch (ArithmeticException e) {
			result = -1;
			System.out.println("숫자는 0으로 나눌 수 없습니다.");
		}
	}
}


🚨 다중 catch문 작성시 주의사항
상위 예외클래스가 하위 예외 클래스보다
아래쪽에 위치해야한다!


3️⃣ finally
finally문은 try 문장 수행 중 예외 발생 여부와 상관없이 무조건 실행됩니다

public class DivideExceptionSample {
    void finalMessage() {
        System.out.println("그럼 수고하세요.");
    }

    public static void main(String[] args) {
        DivideExceptionSample sample = new DivideExceptionSample();
        int result;
        try {
            result = 5 / 0;
            sample.finalMessage();       // 이 코드는 실행되지 않는다.
        } catch (ArithmeticException e) {
            result = -1;
            System.out.println("숫자는 0으로 나눌 수 없습니다.");
        } finally {
            sample.finalMessage();    // 이곳에서는 예외와 상관없이 무조건 수행된다.
        }
    }
}


💬 사용자 정의 예외를 만들 수 있나요?
네! 사용자 정의 예외 클래스는 아래 예외로 선언이 가능합니다.
✔️ 일반 예외 -> Exception 상속
✔️ 실행 예외 -> RuntimeException 상속

/* 일반 예외 */
public class XXXException extends Exception { 
	public XXXException() { } // 매개변수 없는 기본 생성자
	public XXXException(String message) {  super(message);  } // 매개 변수 있는 생성자
}

or 

/* 실행 예외 */
public class XXXException extends RuntimeException {
	public XXXException() { }
	public XXXException(String message) {  super(message);  }
}


4️⃣ `throw` vs `throws` 차이
- throw: 메소드 안에 사용
- throws: 메소드 선언부에서 사용(해당 메소드가 처리하지 않은 예외를 호출자에게 전달한다는 의미를 내포)

728x90
320x100