Java
forEach로 예외처리하기 (Unhandled exception: java.lang.Exception 에러 해결)
열심히 사는 우진
2022. 11. 2. 03:59
반응형
forEach는 throws를 할 수 없다.
static void checkIsOne(int number) throws Exception{
if (number == 1) {
throw new Exception("oh no");
}
System.out.println(number);
}
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
list.stream().forEach(a -> checkIsOne(a)); // Unhandled Exception 발생!
forEach문 안의 메서드가 예외를 발생시키면,
Unhandled exception: java.lang.Exception 라는 에러 메세지가 출력됩니다.
일반 메서드에서 예외가 발생하면 throws를 사용하면 되었는데요,
forEach문에서는 throws 키워드를 적용할 수 없어 난감했습니다.
하지만 try-catch문으로 간단하게 해결할 수 있었습니다.
try-catch 사용!
예외를 처리하는 방법에는 대개 throws와 try-catch를 사용하는 방법이 있습니다.
throws는 상위로 예외를 보내는 것입니다.
static void checkIsOne(int number) throws Exception{
if (number == 1) {
throw new Exception("oh no");
}
System.out.println(number);
}
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
// Unhandled Exception 해결
list.stream().forEach(a -> {
try {
checkIsOne(a);
} catch (Exception e) {
System.out.println(e);
}
});
try-catch문은 예외를 직접 처리합니다.
forEach문 안에 try-catch를 사용하면, Unhandled exception이 사라집니다.
간단한 오류를 해결하면서,
throws와 try-catch의 차이에 대해 이해할 수 있었네요.
감사합니다.
반응형