K-DigitalTraining 강의/1. Java
[2주차] 53. 예외처리, throws를 이용해 예외를 다른 곳에서 처리하기
이대곤
2022. 6. 1. 18:58
* 예외를 다룰 때 throws 의 기능
실행중 호출되는 서브함수에서 예외가 발생할 예정이라고 하자.
원래는 예외가 발생한 서브함수에서 try-catch로 예외를 처리해 주었는데
throws를 이용하면 발생한 예외를 호출된 쪽에서 처리할 수 있다.
즉, 예외는 서브함수에서 발생하더라도 서브함수가 호출된 main함수에서 try-catch로 예외를 처리해 줄 수 있는 것이다.
코드
public class Ex07_04_예외처리 {
public static void main(String[] args) {
try {
sub();
} catch (ArithmeticException e) {
System.out.println("main에서 예외처리");
}
}
static void sub() throws ArithmeticException {
int result = 10 / 0; // 예외발생 new ArithmeticException
System.out.println(result);
}
}
실행결과
main에서 예외처리