본문 바로가기

Java

throw, checked - unchecked 예외, throw

throw : 예외를 발생시키는 키워드이다. 

ex)   throw new Exception("message");    // 예외발생 

public class Test { 
	
	public static void main(String[] args) {
		try {
			throw new Exception("message");
		} catch (Exception e) {
			System.err.println("예외 메시지 출럭 : " + e.getMessage());
		} 
	}
}
더보기

public class Test { 

    public static void main(String[] args) {
        // 은폐의 목적으로 try-catch문 사용 
        try {
            throw new RuntimeException();
        } catch (Exception e) {
        }

    }
}

 

checked 예외

컴파일러단에서 try - catch를 잡으라고 알려준다. ( 강제성 부여 )

Exception 클래스와 Exception클래스를 상속받을 클래스들을 의미한다. 

 

unchecked 예외

컴파일러가 예외 처리를 강제하지 않는다. 

RuntimeException 클래스와 RuntimeException클래스를 상속받은 클래스들을 의미한다. 

 

 

예외 선언하기

throws : 예외 떠넘기기 키워드

메서드에서 발생한 예외를 메서드를 호출한 쪽에서 try-catch문으로 예외처리를 하도록 강제하는 것.

ex)   [반환형] [메서드이름] throws [발생가능Exception1], [발생가능Exception2], .. {

    // 소스코드 

}  

throws에서는 checked Exceotion 뿐만 아니라 unchecked Exceotion도 적을 수 있지만 checked Exceotion만 적는것이 정석이다.

public class Test {

	public static void main(String[] args) throws Exception{
		method1();
	}
	
	static void method1() throws Exception { 
		throw new Exception();
	}
// 실행결과 : main에서도 Exception을 throws해 처리하지 않으면 JVM의 기본예외처리기가 처리해준다.
// Exception in thread "main" java.lang.Exception
//	at test.Test.method1(Test.java:10)
//	at test.Test.main(Test.java:6)
}

 

public class Test {

	public static void main(String[] args) /* throws Exception */ {
		method1(); // 예외처리에 대한 강제성 부여
	}
	
	static void method1() throws Exception { 
		throw new Exception();
	}
	
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Java' 카테고리의 다른 글

Exception re-throwing, try-catch문에서의 return  (0) 2023.05.26
사용자 정의 예외  (0) 2023.05.24
예외  (0) 2023.05.22
익명 클래스(anonymous class)  (0) 2023.05.18
초기화 블록  (0) 2023.05.15