티스토리 뷰


try-catch와 throw 


public class ThrowsException {


static int a, b;


public static void main(String[] args) {

// TODO Auto-generated method stub


try {

a = Integer.parseInt("12");

b = Integer.parseInt("0");

method1();

} catch (ArithmeticException e) {

System.out.println("ArithmeticException 처리 루틴 : ");

System.out.println(e + " 예외 발생");

} catch (NumberFormatException e) {

System.out.println("NumberFormatException 처리 루틴 : ");

System.out.println(e + " 예외 발생");

} catch (Exception e) {

System.out.println("나머지 모든 예외 처리 루틴 :");

System.out.println(e + " 예외 발생");

}


// 발생되는 예외의 종류에 따라 캐치문이 결정되고 메시지가 출력된다. (e포함)

// 예외는 throws를 사용하여 method1과 2로 보내져 처리하게 된다.

}


//숫자가 아닌경우의 예외 받음

public static void method1() throws NumberFormatException {

// TODO Auto-generated method stub


System.out.println("매개변수로 입력받은 두 개의 값 : ");

System.out.println("a = " + a + " b = " + b);

System.out.println("=======================");

method2();

}


//연산 결과에 대한 예외 받음

public static void method2() throws ArithmeticException {

// TODO Auto-generated method stub

System.out.println("최종 메소드 예외 발생 문장 수행 전");

System.out.println("a를 b로 나눈 몫 = " + (a / b));

System.out.println("최종 메소드 예외 발생 문자 수행 후");


}

}


결과 : 


정상적인 경우

매개변수로 입력받은 두 개의 값 : 

a = 12 b = 2

=======================

최종 메소드 예외 발생 문장 수행 전

a를 b로 나눈 몫 = 6

최종 메소드 예외 발생 문자 수행 후




문자가 섞여 있는 경우

NumberFormatException 처리 루틴 : 

java.lang.NumberFormatException: For input string: "0a" 예외 발생



나누는 수가 0인 경우

매개변수로 입력받은 두 개의 값 : 

a = 12 b = 0

=======================

최종 메소드 예외 발생 문장 수행 전

ArithmeticException 처리 루틴 : 

java.lang.ArithmeticException: / by zero 예외 발생





'java,web study > 2주차 (7월 8일~14일)' 카테고리의 다른 글

UserException  (0) 2013.07.14
오라클 설치  (0) 2013.07.12
예외처리 02  (0) 2013.07.11
예외처리 01  (0) 2013.07.11
익명이너클래스 (Anonymous Inner Class)  (0) 2013.07.11
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   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
글 보관함