예외 처리 -- 2

2025. 6. 12. 12:07언어/자바

 

 

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;

 

}

'언어 > 자바' 카테고리의 다른 글

Object  (0) 2025.06.13
디자인 패턴 - 싱글톤 패턴  (0) 2025.06.12
예외 처리  (0) 2025.06.11
equals vs == 차이  (0) 2025.06.11
Object 부모 클래스  (0) 2025.06.09