멀티 캐치 (Java 7 이상)를 사용하여 사용자 정의 예외 클래스를 생성합니다. 이것은 제가 만든 수업입니다.멀티 캐치에서 예외 클래스를 확인할 수 없습니다.
public class CustomException extends Exception{
public CustomException() {
System.out.println("Default Constructor");
}
public CustomException(ArithmeticException e, int num){
System.out.println("Divison by ZERO! is attempted!!! Not defined.");
}
public CustomException(ArrayIndexOutOfBoundsException e, int num){
System.out.println("Array Overflow!!!");
}
public CustomException(Exception e, int num){
System.out.println("Error");
}
및 위 클래스는 다음과 같은 클래스에서 확장 : 다음 코드를 참조하십시오.
import java.util.Scanner;
public class ImplementCustomException extends CustomException {
public static void main(String[] args) throws CustomException {
int num = 0;
System.out.println("Enter a number: ");
try(Scanner in = new Scanner(System.in);){
num = in.nextInt();
int a = 35/num;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException|ArrayIndexOutOfBoundsException e){
throw new CustomException(e, num);
}
}
}
나는 이것을 실행하려고 할 때마다 "예외"가있는 동일한 생성자를 호출합니다. 그 이유는 무엇입니까?
그러나 멀티 캐치 구문을 다음 코드로 바꿀 경우. 예상대로 작동하고 있습니다.
멀티 캐치를 사용하고 필요한 예외를 던질 수 있도록 가능한 변경 사항을 알려주십시오.
'!!!'에 너무 익숙해지지 마십시오. 어떤 사람들에게는 눈살을 찌푸리게됩니다. – glglgl
사이드 노트 : 사용자 정의 예외가 정보를 잃어 버리지 않도록 설정되어 있는지 확인하십시오. 내 말은 : 배열 인덱스를 벗어나서 커스텀 예외를 만들었지 만 코드에서 그 예외를 완전히 잊어 버리는 것이다. 의미 : 범위 밖의 배열 인덱스가 발생했음을 알았지 만 스택 추적 및 메시지가 없다면 나중에 문제를 디버그하는 것이 매우 어려울 것입니다 **. – GhostCat