Code Archive/JAVA

Step11. Exception(예외처리)

쌍큐 2014. 9. 12. 14:10


**Exception 처리(예외 처리)**

compile error : 컴파일 시 발생하는 에러

Exception , Error : 실행시 발생하는 예외 및 에러


프로그램 수행시  Exception이 발생해도 강제 종료되지 않게 적절하게 대처하여

프로그램을 정상적으로 수행하도록 한다.



-Exception 문법 -

try : Exception 발생예상 지점 블럭

catch : Exception 처리 ( Exception 예외에 대한 대안 )


finally : Exception 발생시 catch 여부와 상관없이 항상 수행


throws : Exception 을 호출한 곳으로 던지는 keyword

throw : Exception 을 고의로 발생시킬 때 사용하는 keyword



사용자 정의 Exception class

class를 만들때 Exception을 상속 받으면 된다.


//사용자 정의 Exception

class AgeException extends Exception{

AgeException(String message){

super(message);

}

}

class Movie{

        //해당 메소드를 호출한 곳으로 익셉션을 던짐

public void enter(int age) throws AgeException{

if(age<=18){

                        //익셉션 강제 발생

throw new AgeException("미성년자 관람 불가");

}

System.out.println("관람가능");

}

}

public class TestReview {

public static void main(String[] args) {

Movie m=new Movie();

//int age=17;

 int age=20;

try{

m.enter(age);

}catch(AgeException ae){

System.out.println(ae.getMessage());

}finally{

System.out.println("finally 항상 수행");

}

System.out.println("정상 수행");

}

}