YYYEJI

[JAVA] 예외처리(throws)란? 본문

Java

[JAVA] 예외처리(throws)란?

YEJI ⍢ 2022. 12. 27. 20:48
728x90

throws란?

자신을 호출하는 메소드에 예외처리의 책임을 떠넘기는 것입니다.

 

 

 

throws 예제 코드입니다.


public static void main(String[] args) {
	
    try {
    	divideByZeroTest(20, 0);
    } catch (ArithmeticException e) {
        System.out.println("ArithmeticException: " + e.getMessage());
    }
    
}

public static void divideByZeroTest(int a, int b) throws ArithmeticException{
    System.out.println("The result is "+ a/b + ".");
}

예외상황이 발생하면 ArithmeticException의 error message가 뜹니다.

- throws는 throw와 다르게 예외선언을 따로 하지 않아도 됩니다.

divideByZeroTest 메소드(method)에 예외처리의 책임을 넘겼기 때문입니다.

 

- divideByZeroTest 메소드(method)를 정의할 때  throws ArithmeticException 코드를 작성하면 됩니다.

 

 

 

 

◡̈