예외 처리 -- 2

static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
/*
* 1. 강제예외발생 : throw new Exception(message);
* 2. 상위 메서드에게 예외 던지기
* throws Exception
* 3. 예외 처리 : try ~ catch ~ finally
* catch(던진 Exception e){e.getMaessage()}로 받는다.
*
* catch문이 여러개일때(다중 catch) 부모 Exception이 제일 아래오도록 한다. 실행순서는 위에서부터 실행
*/
// new 생성해서 메서드 참조하기
IDFormetTest idform = new IDFormetTest();
try {
int age = idform.readAge();
System.out.println(age);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
// static으로 해당 메서드 참조하기
try {
int age = readAge();
System.out.println("나이 : " + age);
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("메시지 : " + e.getMessage());
} finally {
scan.close();
System.out.println("<<< finally >>>");
}
System.out.println("<<< 정상종료 >>>");
}
public static int readAge() throws Exception {
System.out.print("나이를 입력하세요. : ");
int age = scan.nextInt();
if(age < 0) {
// 1. 강제예외발생 : throw new Exception(message);
---> 예외 () 안에 내가 원하는 메시지를 상위 부모로 전달 가능함

throw new Exception("나이는 0보다 커야합니다.");
}
return age;
}