출처 :http://cafe.naver.com/javasolution/58

* Exception은 2가지 종류가 있다.

시스템 정의 Exception ( System Define Exception ) 과 사용자정의 Exception ( User Define Exception).


 

1. 다음과 같은 이름으로 사용자정의 Exception를 작성하시오. ( UserDefineException.java  )




 

2. 다음 코드를 실행시키면 에러가 발생한다. UserDefineException으로 예외처리하시오.

public class ExceptionTest {


 

 public static void main ( String [ ] args){

      a();

}//

 public static void a(){

     b();

}//

 public static void b(){

String name;

Systme.out.println(  name.charAt( 0 ) );

 }//

}//


1번정답:

public class UserDefineException extends Exception {


public UserDefineException( String mesg){

super( mesg );
}

}
사용자정의클래스를 만들때에는 구현내용은 정해진것이 없지만 반드시 Exception클래스를
상속받아야 한다. 일반적으로 문자열을 처리할수 있는 생성자를 만드는것이 보통이다.
또한 필요에 의해서 인스턴스변수 및 메소드도 추가할 수 있다.



2번정답:

public class ExceptionTest {


public static void main ( String [] args ){

try{
a();
}catch( UserDefineException u ){
System.out.println( u.getMessage() );
}
}//

public static void a() throws UserDefineException{

b();

}//
public static void b() throws UserDefineException{

try{
String name = null;
System.out.println( name.charAt(0) );
} catch( NullPointerException e){ // 실제로 catch한것은 NullPointerException 이지만 사용자정의클래스를 생성하여 처리.
throw new UserDefineException( "널포인터 발생");
}
}//

}//
어느 메소드에서나 예외처리를 할 수 있지만 main에서 처리하게 구현함.
이와 같은 예외처리 방법을 반드시 숙지할것

Posted by 나비:D
:
BLOG main image
by 나비:D

공지사항

카테고리

분류 전체보기 (278)
Programming? (0)
---------------------------.. (0)
나비의삽질 (5)
Application (177)
SQL (51)
Web (27)
etc. (14)
Omnia (0)
---------------------------.. (0)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

달력

«   2024/04   »
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
Total :
Today : Yesterday :