AssertionError #88
jupyter471
started this conversation in
지식 공유하기
Replies: 1 comment
-
|
또한, 일부러 AssertionError를 던지는 경우도 있다고 합니다 **"절대 발생하지 않아야 하는 경우"**를 더 명확하게 표현하려 할 때 씁니다. 예를 들어, switch문에서 열거형(enum) 값이 빠짐없이 처리됐어야 하는데, 불가능한 경우: enum Color { RED, GREEN, BLUE }
void processColor(Color color) {
switch (color) {
case RED -> System.out.println("Red");
case GREEN -> System.out.println("Green");
case BLUE -> System.out.println("Blue");
default -> throw new AssertionError("Unknown color: " + color);
}
}여기서 default는 이론상 절대 실행되지 않아야 하니까, 이런 경우는 **"정상적인 프로그램 흐름"이 아니라 "불가능한 흐름을 탐지"**하는 것이기 때문에 예외적으로 인정됨! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
아이템 70에 Assertion 예외가 언급되는데, 어떤 용도인지 왜 다른 에러와 달리 구현되어도 되는지 궁금해서 찾아보았습니다
❓왜 AssertionError는 괜찮은가?
assert는 코드의 논리적 전제가 맞는지 검증하는 용도로 사용한다
ex) 파라미터 유효성 검사
(아이템 어디였지)
ex)
이 전제가 깨지면 AssertionError를 던지고 프로그램을 중단시켜 개발자가 문제를 빠르게 발견할 수 있도록 한다
"애초에 여기까지 코드가 도달하면 프로그램 논리 자체가 깨진 거다." 라는 의미 내포
즉, AssertionError는 "복구"하려는 게 목적이 아니라, 버그를 즉시 발견하려는 목적으로 개발자용이다
원래는 "정상 흐름 + 복구 고려 대상"만 비검사 throwable을 던져야 한다.
AssertionError는 "정상 흐름"이 아니기 때문에 RuntimeException 하위가 아니어도 예외적으로 허용되는 것.
비교
Beta Was this translation helpful? Give feedback.
All reactions