- 자바의 예외 처리 방법은 try catch 도 있지만, throws 키워드를 이용하는 방법도 있다.
- throws키워드를 이용하여 예외를 호출한 클래스에 위임(던진다,throws)한다.
- 자바의 메서드 호출 방법을 이용하여 메서드 내에서 발생한 예외를 처리하는 방법이다.
형식
public 리턴타입 메서드명 (매개변수) throws 예외 클래스명{
}
public void callee() throws Exception{ //예외를 호출한 메인클래스로 던진다.
특징
- 예외 발생 시 발생한 예외를 메서드를 호출한 곳으로 전달하여 예외 처리를 한다.
- 컴파일러가 호출한 곳을 기억하고 있다.
- 최초 메서드를 호출한 main()메서드에서는 try/catch문으로 예외 처리를 해야 한다.
- 실제 개발에서는 소스 양이 많아 지게 되게 되고 예외 처리는 최상위 메서드에서 일괄적으로 처리해주면 간결해지고 가독성이 높아진다.
package com.java.exception;
public class Exception05_1 {
public void callee() **throws Exception** { // 피 호출자
System.out.println("Callee1 메서드 시작");
//try {
int[] arr = new int[2];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
for(int num:arr)
System.out.println(num);
// }catch(ArrayIndexOutOfBoundsException e) { //예외 처리 구문
// e.printStackTrace();
// System.out.println("ArrayIndexOutOfBoundsException 예외가 발생했습니다.");
//
// }
System.out.println("Callee1 메서드 종료");
}
}
package com.java.exception;
public class Exception05_2 {
//throws Exception를 통해서 호출자에게 예외를 던져준다
public void callee() **throws Exception** { // 피 호출자
System.out.println("Callee2 메서드 시작");
// try {
int[] arr = new int[2];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
for(int num:arr)
System.out.println(num);
// }catch(ArrayIndexOutOfBoundsException e) { //예외 처리 구문
// e.printStackTrace();
// System.out.println("ArrayIndexOutOfBoundsException 예외가 발생했습니다.");
//
// }
System.out.println("Callee2 메서드 종료");
}
}
package com.java.exception;
public class Exception05 {
//caller(호출자): main메서드에서 callee()호출
//시나리오
//1)모든 코드가 정상 작동하는 경우(예외 처리 x)
//2)Exception05_1에서 예외가 발생해서 예외 처리를 한 경우
//3)Exception05_2 클래스를 추가하고 메서드를 호출한다.
//4)각 피호출 클래스에서 예외 처리 코드를 주석 처리하고,호출 클래스에서 예외 처리를 한다.
//5)Exception05_1의 callee메서드에서 예외가 발생해서 main에서 예외 처리하고 종료된다.
//6) throws Exception 을 통해 호출자인 (main 메서드)에게 예외를 던져준다.
public static void main(String[] args) {
//Exception > throws
try {
//문제1) Exception05_1클래스에 있는 callee를 호출해서 실행하시오.
Exception05_1 ex = new Exception05_1();
ex.callee(); //여기서 멈추고 예외를 catch문에 던져준다.
Exception05_2 ex1 = new Exception05_2();
ex1.callee();
System.out.println("Hello");
}catch(Exception e) {
//e.printStackTrace();
System.out.println("예외를 처리했습니다.");
}
System.out.println("World");
}//main
}