ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Java - throws
    Java 2018. 1. 23. 10:33
    반응형
    < throws >

    public class Main {

        public static void main(String[] args) throws Exception { // jvm으로 exception 넘기기
            
            Sub sub = new Sub();
            sub.method1();
    // jvm은 exception 메세지만 출력
        }

    }


    public class Sub {

        public void method1() throws Exception { // NumberFormatException, Main으로 넘기기
            method2();
        }

        public void method2() throws Exception { // 호출 되었던 method()1로 넘기기
            Integer.parseInt("sdasd"); // NumberFormatException
        }

    }




    < Custom Exception >

    public class ReserveException extends RuntimeException { // RuntimeException도 Exception에 포함.

        public ReserveException(String message) {
            super(message);
        }
    }


    public class JoinMember {

        String[] reserved= {"admin", "tester", "member"};
        public void regid(String id) throws Exception{
            // 입력된 id가 reserved 값과 일치 하면 예외 발생
            
    //      for(int i = 0; i< reserved.length; i++) {
    //          if(reserved[i].equals(id)) {
    //              System.out.println(reserve[i] + "id가 같습니다.");
    //          }
    //      }
            
            for(String s : reserved) {
                if(s.equals(id)) {
                    System.out.println(s+ "이 이미 있는 ID입니다.");
                    // throw new 000Exception("msg") 해당 exception을 발생 시킨다.
                    // throw new Exception("Test 일반 예외 발생"); // try-catch 강제됨, 일반예외일때는 try-catch 해야됨.
                    throw new ReserveException(id + "는 예약어 입니다."); // CustomException에 Exception을 extends 시킨다.
                }
            }
    }
    }


    public class Main {

        public static void main(String[] args) throws Exception {
            
            JoinMember jm = new JoinMember();
            jm.regid("admin");
            
        }

    }


    // 일반 예외는 try-catch가 강제 된다.

    // 예외를 따로 만들 때, 예외를 상속 받아야 한다.

    // Web에서 NullPointException가 많이 나온다.








    반응형

    'Java' 카테고리의 다른 글

    Java - StringBuffer & StringBuilder  (0) 2018.01.23
    Java - String  (0) 2018.01.23
    Java - Try, Catch  (0) 2018.01.23
    Java - Api 참고 사이트  (0) 2018.01.23
    Java - Interface  (0) 2018.01.19

    댓글

Designed by Tistory.