2013년 7월 1일 월요일

(130701) 6일차 ExceptionTest.java (Exception 예외 처리 테스트)

 - Exception : 객체(클래스)
 : Exception 클래스 : 자바 프로그래밍에서 발생 가능한 에러를 정의한 클래스를 말함.

파일을 읽어들이기 위한, File f = new File("파일의 이름"); // 의 경우 파일의 이름에는 String 타입으로만 쓰면 된다. 그렇기 때문에 String 타입만 넣으면 소스코드 에러는 없으나, 파일을 찾지 못하면 런타임 에러가 발생한다. 여기서 Exception 클래스는 자주 사용되는 에러를 정의해놓은 클래스라고 할 수 있다.

 - Exception 수업의 목표 : Exception이 발생했을 때 프로그램이 계속 돌게 해주는 것이 목표.

 - Exception 처리 방법 : try, catch, finally
Exception이 발생한 곳에서 직접 처리하는 방법
try {
//Exception이 발생할 수 있는 코드
//protected code 
}catch(발생예상Exception타입 identifier){
//Exception이 발생했을 때 실행할 코드
}catch(발생예상Exception타입 identifier){
//Exception이 발생했을 때 실행할 코드

   :
}catch(발생예상Exception타입 identifier){
//Exception이 발생했을 때 실행할 코드
} finally {
//Exception이 발생하든 안 하든 항상 실행
//try{}안에 return 키워드가 있어도 finally를 실행한 후 return 한다.
//System.exit()를 만나면 실행 중지.
}


 - 소스
public class ExceptionTest {

public static void main(String[] args) {

/* System.out.println("잘 나온다 1111");
int result = 30/0; // 소스 에러는 없지만 Exception 에러는 발생
System.out.println("잘 나온다 2222"); // 위에서 Exception 에러가 나면 출력을 하지 않는다.
System.out.println("잘 나온다 3333"); */

System.out.println("잘 나온다 1111");
try{
// 예외처리에 대한 모든 Exception을 알 수 없다.
int result = 30/0; // 소스 에러는 없지만 Exception 에러는 발생
int result2 = Integer.parseInt("aaaaa");
System.out.println("잘 나온다 2222"); // 출력하고 싶으면 try 밖에다 써줘야 한다.

} catch (ArrayIndexOutOfBoundsException e){
// 위에서 필요한 Exception이 아니므로 예외처리가 안됨
} catch (ArithmeticException e){
e.printStackTrace(); // 예외처리를 해주고, 에러난 부분을 출력해주며, 프로그램을 끝까지 종결시킴
} // 하지만 모든 Exception을 외울 수 없고, Exception은 다형성에 의해 Exception 되므로 다음과 같이 쓴다.
catch (Exception e){
e.printStackTrace();
} finally {
System.out.println("무조건 실행"); // 무조건 출력. 써도 되고 안써도 된다.
}
System.out.println("잘 나온다 3333");
}
}


 - 결과