본문 바로가기

Java/JAVA STUDY

JAVA 사용자가 지정한 예외 처리

AgeInputException class

자바가 만들어놓은 Exception class를 상속

constructor- super를 통해 문자열1 입력 

 

Main class ThrowsFromUpperMethod

try catch문.

 

catch (AgeInputException e) {

            e.printStackTrace();

        }

 

printStackTrace 활용

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package exam09;
 
import java.util.Scanner;
 
class AgeInputException extends Exception{
    AgeInputException(){
        super("유효하지 않은 나이를 입력하셨습니다."); 
   }
}
 
public class ThrowsFromUpperMethod {
    public static void main(String[] args) {
        int age = 0;
        
        try {
            age = callAge();
        } catch (AgeInputException e) {
            e.printStackTrace();
        }
        
        if(age == 0) {
            System.out.println("나이값 입력 오류.");
        }else {
            System.out.println("당신의 나이는 "+age+"이군요.");
        }
 
    }
    
    public static int callAge() throws AgeInputException {
        int age = 0;                //예외를 메서드 호출 쪽에서 처리
        
 
        age = readAge();  
 
        
        return age;
    }
    
    public static int readAge() throws AgeInputException{
        Scanner input = new Scanner(System.in);
        
        System.out.print("나이를 입력하세요 : ");
        int age = input.nextInt();
        
        if((age < 0)||(age>120)) {
 
                                     //만든 자료형 사용하려면 인스턴스 생성해야
            AgeInputException excpt = new AgeInputException();
            throw excpt; // throw >> catch문을 호출! 이미 자바가 구현해놓은 기능.
        }
        
        return age;
    }
 
}
cs