개발/Java

[Java] throw, throws 차이 및 사용법

Monsh 2021. 2. 11. 20:40
반응형
  throw throws
역할 명시적으로 exception을 발생 exception을 선언
문법 throw + instance throws + class
위치 used in method used with method signatures
제한 한 번에 하나의 exception만 발생 가능 한 번에 여러 개의 exception 등록 가능

 

아래의 예제 코드는 의미만 통할 수 있게 작성했습니다.

class ExceptionTest {
	
    method main {
        try {
        	MakeException;
        } catch(MadeException e) {
        	println("MadeException Found");
        } finally {
        	println("In this example, [finally] is not required.");
        }
    }
    
    // throws: Declare an exception
    method MakeException throws MadeException {
    	for(int i=0; i<10; i++){
        	try {
            	if(i != 6)
                	println(i + " passed.")
                else
                	// throw: Explicitly raise an exception
                	throw new MadeException();
            } catch(MadeException e) {
            	println("MakeException made a MadeException.");
                throw e;
            }
        }
    }
}

 

위 코드의 결과는 아래와 같을 것입니다.

0 passed.
1 passed.
2 passed.
3 passed.
4 passed.
MakeException made a MadeException.
MadeException Found
In this example, [finally] is not required.

 

반응형