본문 바로가기
java

[java 자바] exception

by 코디드 2023. 6. 22.

catch() 순서는 하위 > 상위 순으로 써야 함. Exception을 제일 마지막에 써야 함.

 

Unreachable catch block for ArrayIndexOutOfBoundsException(예시로 든 예외). 
It is already handled by the catch block for Exception

 

그렇게 하지 않을 경우 위와 같은 에러가 뜬다.

Exception 만 쓰면 모든 예외 처리가 가능하기 때문에 사실 Exception 뒤에는 다른 예외를 쓰는게 의미가 없다.

 

-모든 예외 클래스는 Exception 클래스를 상속 받음

-하위 클래스는 상위 클래스에 대입 가능(반대는 불가)

-같은 실행문을 쓰는 다른 종류의 Exception 들을 동시에 처리할 때 사용

 

 

public class ExceptionTest1 {
	
	public ExceptionTest1() {}
	
	public void start() {
		
		Scanner scan = new Scanner(System.in);
		
		try {
			
			System.out.print("첫번째 수=");
			int num1 = scan.nextInt();
			System.out.print("두번째 수=");
			int num2 = scan.nextInt();
			
			int hap = num1 + num2;
			int cha = num1 - num2;
			int mul = num1 * num2;
			int div = num1 / num2;	//<-------------
			
			//		   5 + 10 = 15
			//		   printf(String format, Object... args)
			System.out.printf("%-5d + %-5d = %7.2f\n", num1, num2, (double)hap);
			System.out.printf("%d - %d = %d\n", num1, num2, cha);
			System.out.printf("%d * %d = %d\n", num1, num2, mul);
			System.out.printf("%d / %d = %d\n", num1, num2, div);
			
			int data[]= {10,20,30};
			System.out.println("배열->"+data[data.length-1]);
			
			
		}catch(InputMismatchException e) {
			System.out.println("숫자를 입력하세요.");
			e.printStackTrace();
			System.out.println(e.getMessage());
		}catch(ArithmeticException ae) {
			System.out.println("두번째 값은 0을 입력하지 마세요.");
			ae.printStackTrace();
			System.out.println(ae.getMessage());
		}catch(ArrayIndexOutOfBoundsException aioe) {
			System.out.println(aioe.getMessage());
		}finally {
			System.out.println("무조건 실행됨.");
		}
		
	}

 

이렇게 try catch finally 까지 다 같이 쓰기도 하고

 

 

public class ExceptionTest3 {
	
	public ExceptionTest3() {}
	
	public void inData() throws Exception {
		Scanner scan = new Scanner(System.in);
		System.out.print("첫번째 수->");
		String n1 = scan.nextLine();//콘솔에서 한줄씩 입력함.(enter 포함)
		System.out.print("두번째 수->");
		String n2 = scan.nextLine();
		int n1Int = Integer.parseInt(n1); // 문자열을 정수형 int로 변환해주는 메소드
		int n2Int = Integer.parseInt(n2);
		divide(n1Int, n2Int);
	}
	
	public void divide(int n1, int n2) throws Exception {
		int result = n1 / n2;
		System.out.printf("%d / %d = %d\n", n1, n2, result);
		array();
	}
	
	public void array() throws Exception {
		int data[] = {25,52,6,4};
		System.out.println(data[4]);
	}

	public static void main(String[] args) {
		
		try {
			ExceptionTest3 et3 = new ExceptionTest3();
			et3.inData();
		}catch(Exception e) {
			System.out.println("예외 발생함.....");
		}

	}

}

 

위에 쓴 예시 처럼

 

public void inData() throws Exception {}

throws 를 통해 예외를 상위로 밀어서 처리하기도 한다.

 

 

 

사용자 정의 예외 클래스

 

1. 클래스 명은 Exception을 마지막 단어로 합성.

  e.g.) 단어+Exception

 

2. api의 Exception 클래스나 RuntimeException 클래스 중 한 개를 상속 받음

 

 

public class MyException extends Exception {
	public MyException() {
		super("1~100 사이의 값이 아닙니다.");
	}
	public MyException(String message) {
		super(message);
	}
}

 

이렇게 사용자 정의 예외 클래스를 만들어주고 Exception을 상속 받은 후

 

 

 

public class MyExceptionTest {
	Scanner scan = new Scanner(System.in);
	
	public MyExceptionTest() {}
	
	public void start() {
		try {
			
            //코드 어쩌구 저쩌구
            
			}else {
				//throw : 강제로 예외 발생시키기
				//throw new MyException();
				
				throw new MyException("1에서 100 사이의 값만 가능해.");
			}
			
		}catch(InputMismatchException ime) {
			System.out.println("정수를 입력하지 않았습니다.");
		}catch(MyException me) {
			System.out.println(me.getMessage());
		}
	}

 

throw 를 통해 강제로 예외를 발생 시켜 준다.