티스토리 뷰

JAVA

Exception handling in Java

seoca 2019. 6. 24. 03:27

 

 

예외처리 (Exception handling) 은 프로그램의 논리에 벗어난 에러인 runtime error를 발견하도록 도와준다. 

 

 

- 사용자정의 exception handling 이 아닌 자바에 자체적으로 내장되어있는 에러클래스의 경우 (e.g. ArithmeticException) 사용자가 새롭게 객체를 정의하지 않아도 JVM에 의해 생성된 인스턴스의 참조값이 전달된다. 

import java.util.Scanner;
class Main{
    public static void main(String[] args){
        System.out.print("Enter two digits: ");
        Scanner keyboard = new Scanner(System.in);
        int num1 = keyboard.nextInt();
        int num2 = keyboard.nextInt();
        try{
            System.out.println("quotient: " + (num1/num2));
            System.out.println("remainder: "+ (num1%num2));
        }catch(ArithmeticException e){ //JVM에 의해 생성된 인스턴스 전달
            System.out.println("Calculation is incomplete");
            System.out.println("e.getMessage()");
        }
        System.out.println("Exit");
    }
}
 

 

 

- throws 를 사용하게 되면 그 메서드에서 어떤 에러가 발생할 지 예측하기 쉬워지며 굳이 예외처리까지 해당 메서드에 담을 필요없이 그 메서드를 사용하는 메서드에서 원하는 방식으로 에러를 처리할 수 있다. 

                    //MenuChoiceException 에러 발생시에 예외처리를 전가시킴
public void inputData() throws MenuChoiceException{
        System.out.println("Start to input data");
        System.out.println("1.Friend, 2.University, 3.Company");
        System.out.print("Enter: ");
        int select = MenuViewer.keyboard.nextInt();
        MenuViewer.keyboard.nextLine();
        PhoneInfo info = null;
 
        if(select < INPUT_SELECT.FRIEND || select > INPUT_SELECT.COMPANY){
            //에러발생시 강제로 error객체생성후 catch실행. 메서드 내에서 예외처리를 수행.
            throw new MenuChoiceException(select);
        }
 
        switch (select){
            case INPUT_SELECT.FRIEND:
                info = friendInput();
                break;
            case INPUT_SELECT.UNI:
                info = univInput();
                break;
            case INPUT_SELECT.COMPANY:
                info = companyInput();
                break;
        }
 
        phoneInfo[curCnt++= info;
        System.out.println("completed the input \n");
    }
    
    
public class Main {
    public static void main(String[] args){
        PhoneManager phoneManager = PhoneManager.initPhoneManager(); //signleton pattern 이니까
 
        while(true){
        //try catch 구문은 throw 보다 세세한 컨트롤이 가능하다.
            try {
                MenuViewer.menuViewer();
                int select = MenuViewer.keyboard.nextInt();
                MenuViewer.keyboard.nextLine(); //nextInt 다음에 nextLine으로 delimiter지우기.
 
                if(select < INIT_MENU.INPUT || select > INIT_MENU.EXIT){
                    throw new MenuChoiceException(select);
                }
 
                switch(select){
                    case INIT_MENU.INPUT: 
                        phoneManager.inputData();
                        break;
                    case INIT_MENU.SEARCH:
                        phoneManager.searchData();
                        break;
                    case INIT_MENU.DELETE:
                        phoneManager.deleteData();
                        break;
                    case INIT_MENU.EXIT:
                        System.out.println("Exit the program");
                        return;
                }
            }
            catch (MenuChoiceException e){
                e.showError();
                System.out.println("You need to enter a number again.");
            }
        }
    }
}