[JAVA] Throws

고민정·2024년 4월 5일

JAVA

목록 보기
18/32


🎇 Throws

Throws
오류를 처리하지 않고 나를 호출 한 쪽에서 처리하라고 넘기는 기능

혹시 예외처리(try-catch-finally)를 처음 들어보시는 분들은 아래 포스트를 읽고 오시는 것을 추천드립니다.
예외처리 포스트 바로가기

Throws 의 사용법은 예외가 발생할 곳에 'throws + 예외명' 을 적어주면 됩니다.

정확한 예외 명을 적어도 좋고, 모든 예외를 통틀어 쓰는 Exception 을 써도 됩니다.
(Exception : 모든 예외의 상위 클래스)

public static int divide(int num1, int num2) throws Exception{
        int result = num1 / num2;
        return result;
    }

위와 같은 경우는 0 으로 나눌 때 예외가 발생합니다.
Exception 을 적어도 되고 ArithmeticException 정확한 예외명을 적어도 좋습니다.

이렇게 오류를 던지면 이제 호출한 쪽에서 오류를 고쳐주면 됩니다.
try - catch 로 예외처리했습니다.

public class ExceptionExam2 {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 0;
        try {
            int result = divide(num1, num2);
        }catch (Exception e){
            System.out.println("Error : " + e.toString());
        }
    }

    public static int divide(int num1, int num2) throws Exception{
        int result = num1 / num2;
        return result;
    }
}

0개의 댓글