Java/모두의 자바

Chapter 09-49 Throws

계란💕 2022. 2. 11. 13:44

09-49.1 Throws

 

  Def) Throws : 해당메서드를 호출한 쪽으로 던지는 키워드이다.

  - 형식 :  throws + 발생할 예외

<hide/>
package javaStudy;
public class ExceptionExam2 {
	public static void main(String[] args) {
		int i = 10;
		int j = 0;
		int k = divide(i, j);
		System.out.println(k);
	}
	public static int divide(int i, int j) throws ArithmeticException{
		int k = i / j;
		return k;
	}
}

  Note) 실행 결과

  (1) ExcaeptionExam2 클래스를 만든다.

  (2) 정숫값 두 개를 입력 받은 뒤 두 정수를 나눈 결과를 반환하는 divide메서드 구현한다. 

  (3) int i, j를 넣고 예외가 발생하도록 j = 0을 입력한다. 

  (4) divide메서드 내부에 내부에서 ArithmeticException이 발생하지 않으려면 try - catch 블록으로 감싸서 예외처리. 

  (5) 그런데 예외를  처리하지 않고 divide 메서드를 호출한 쪽에 예외르 처리하라도 넘길 수 있다.

  - 이렇게 내가 처리하지 않고 호출한 쪽에서 처리하라고 넘길 수 있는 키워드가 바로 throws이다.

 

 

09-49.2 throws 적용 예제

<hide/>
package javaStudy;
public class ExceptionExam2 {
	public static void main(String[] args) {
		int i = 10;
		int j = 0;
		int k = divide(i, j);
		System.out.println(k);
	}
	public static int divide(int i, int j) throws ArithmeticException, ClassCastException{
		int k = i / j;
		return k;
	}
}

  - throws ArithmeticException: ArithmeticException라는 오류는 넘긴다고 작성한다. 

  - throws ArithmeticException, ClassCastException : 콤마를 이용해 예외를 여러 개 보낼 수 있다. 

  - 49장에서 공부했듯이 Exception은 모든 예외들의 상위 클래스이다. 

  - 따라서, throws Exception 라고 하면 메서드에서 발생하는 모든 예외를 넘길 수 있다.

  

 

09-49.3 위 예제에 try - catch 적용한 경우

<hide/>
package javaStudy;
public class ExceptionExam2 {
	public static void main(String[] args) {
		int i = 10;
		int j = 0;
		try {
			int k = divide(i, j);
			System.out.println(k);
		}catch(ArithmeticException e){
			System.out.println(e.toString());
		}
	}
	public static int divide(int i, int j) throws ArithmeticException, ClassCastException{
		int k = i / j;
		return k;
	}
}

  Note) 실행 결과

  - 예외 처리할 경우에 try-catch를 적용한다. 

  - 예외가 발생해서 프로그램을 종료하는 게 아니라 예외를 잘 처리한다. 

 

 

09-49.4 Throws 실습 예제

 

ExceptionExam 클래스의 get50thItem메서드는 매개변수로 받은 array의 50번째 값을 return한다. 만약 array 의 크기가 50보다 작을 경우에는 ArrayIndexOutOfBoundsException이라는 예외가 생긴다.  get50thItem ArrayIndexOutOfBoundsException을 throws 하도록 정의하라.

 

<hide/>
package javaStudy;
public class ExceptionExam {
//정답	public int get50thItem(int [] array) throws ArrayIndexOutOfBoundsException {
		return array[49];
	}
}

  (1) 배열이 50보다 큰 경우

<hide/>
package javaStudy;

public class ExamExam {
	public static void main(String[] args) {
		ExceptionExam ex = new ExceptionExam();
		int num = ex.get50thItem(new int[100]);
		System.out.println("array 배열의 50번째 요소의 값: " + num);
	}
}

  Note) 실행 결과: array 배열의 50번째 요소의 값: 0

 

  (2) 배열이 50보다 작은 경우

<hide/>
package javaStudy;
public class ExamExam {
	public static void main(String[] args) {
		ExceptionExam ex = new ExceptionExam();
		int num = ex.get50thItem(new int[30]);
		System.out.println("array 배열의 50번째 요소의 값: " + num);
	}
}

  Note) 실행 결과

  - 메서드 선언부 뒤에 throws예외 객체로 정의한다. 

  - 예외 객체는 구체적인 예외명을 사용해도 되고 Exception으로 모든 예외 객체를 처리하게 보내도 된다. 

  - 배열의 크기가 50보다 작다면 return array[49] 실행될 때 배열의 크기를 벗어난 인덱스에 접근하면서 ArrayIndexOutOfBoundsException을 발생시킨다. 

  - 메서드를 호출한 쪽에서 처리하도록 throws하면 된다.