Java - Runtime Exception와 throw

c.Hano·2024년 11월 22일

자바

목록 보기
8/17
예시.

public class Main {
    public static void main(String[] args) {
        try { //예외가 발생할 가능성이 있는 코드를 이 블록 안에 작성한다.
            int numerator = 10; // 나눗셈의 분자
            int denominator = 0; // 나눗셈의 분모
            int result = numerator / denominator; // 0으로 나누기 시도
            System.out.println("결과: " + result); // 결과 출력
            // 위에서 자연수를 0으로 나누니 오류가 발생하였다.
            // 위에서 오류가 발생하였으니 해당 코드는 실행되지 않는다.
        } catch (ArithmeticException e) {
            System.out.println("오류 발생: " + e.getMessage()); // 오류가 발생하였으니 잡아야한다. catch를 통해 오류를 잡았다.
        } finally {
            System.out.println("프로그램이 종료되었습니다."); // 항상 실행되는 블록
        }
    }
}

** 위에서 자연수를 0으로 나누는 오류가 발생하였는데 왜 throw new 를 하지 않았는가 ? -> ArithmeticException은 Runtime Exception 이기 때문이다. Runtime Exception 은 Java에서 자동으로 던져준다. 즉, 개발자가 명시적으로 throw를 호출하지 않아도 자동으로 예외를 throw 해준다.

** Runtime Exception의 주요 하위 클래스
| 클래스 이름 | 쓰는 상황 |
| ArithmeticException | 수학적인 오류가 발생할 때 던져지는 예외 |
| NullPointerException | 객체가 null인데 메서드나 속성에 접근하려고 하면 발생 |
| IndexOutOfBoundsException | 배열이나 리스트의 인덱스가 범위를 벗어날 때 발생 |
| IllegalArgumentException | 메서드에 잘못된 인자를 전달했을 때 발생 |
| NumberFormatException | 문자열을 숫자로 변환할 때 문제가 발생 (위 클래스의 하위 클래스이다.) |

RuntimeException을 사용한 실용적 예제
public class Main {
    public static void main(String[] args) {
        try {
            String input = "10";
            int number = Integer.parseInt(input); // NumberFormatException 가능성
            //parseInt는 문자열을 정수로 변환하는 기능이다.
            //Interger.parseInt()식으로 사용한다.
            
            int result = number / 0; // ArithmeticException 발생 가능성
            System.out.println("결과: " + result);
        } catch (ArithmeticException | NumberFormatException e) { 
        //오류가 발생하였지만 두개의 클래스가 모두 런타임예외의 하위 클래스 이므로 throw 를 하지 않아도 된다.
        
            System.out.println("오류 발생: " + e.getMessage());
        }
    }
}
profile
꼬질이

0개의 댓글