//예외처리 기본 실습
//정상적으로 컴파일 but 비정상 수행 : 런타임 에러
//if문을 이용한 예외처리
public class ExceptionEx01 {
public static void main(String[] args) {
System.out.println("프로그램 시작");
//에러발생 : 0으로 입력되는 것을 막아줌.
int a = Integer.parseInt(args[0]);
if(a==0){
System.out.println("0은 입력될 수 없습니다.");
System.exit(0);
}
int num = 3 / a;
// String[] arr = new String[2];
// arr[0] = "홍길동";
// arr[1] = "박문수";
// arr[2] = "뚝배기"; //에러발생
System.out.println(num);
System.out.println("프로그램 종료");
}
}
출력물
프로그램 시작
0은 입력될 수 없습니다. //0을 입력했을 경우
//예외처리 기본 실습2
public class ExceptionEx02 {
public static void main(String[] args) {
System.out.println("프로그램 시작");
int a = Integer.parseInt(args[0]);
try{
int num = 3 / a;
System.out.println("결과값 : " + num);
System.out.println("정상종료");
}catch(ArithmeticException e){ //e를 통해서 Exception의 상황을 알아볼 수 있음
//ArithmeticException : 산술, 연산과정에서 허용되지 않는 예외처리
System.out.println("Exception 발생원인 : " + e.getMessage());
//e의 메세지를 받아옴
System.out.println("Exception 클래스 : " + e.toString());
//e의 메세지를 받아옴
// e.printStackTrace(); //Exception 메세지 전부를 받아옴
System.out.println("비정상종료");
}finally{
//정상이던 비정상이던 무조건 실행 finally
System.out.println("무조건 실행");
}
System.out.println("프로그램 종료");
}
}
출력물
프로그램 시작
Exception 발생원인 : /by zero //0을 입력할 경우
Exception 클래스 : java.lang.ArithmeticException: / by zero //0을 입력할 경우
비정상종료 //0을 입력할 경우
무조건 실행
프로그램 종료
//예외처리 기본 실습3
public class ExceptionEx03 {
public static void main(String[] args) {
System.out.println("프로그램 시작");
//<Exception 종류>
//ArratyIndexofBoundException
//NumberFormatException
//ArithmeticExcetion
//<해결방법>
//1. if
//2. try ~ catch
try{
int a = Integer.parseInt(args[0]);
int num = 3 / a;
}
// catch(Exception e){
// System.out.println("잘못된 입력입니다.");
// } //가장 상위 예외처리를 가장 위에 쓸 경우 밑에 예외처리에서 에러 발생
catch(ArrayIndexOutOfBoundsException e){
System.out.println("값을 입력하셔야 합니다.");
}catch(NumberFormatException e){
System.out.println("숫자를 입력해주세요.");
}catch(ArithmeticException e){
System.out.println("0은 입력 불가입니다.");
}catch(Exception e){
System.out.println("잘못된 입력입니다.");
} //가장 상위 예외처리는 마지막에 써줘야함.
System.out.println("프로그램 종료");
}
}
출력물
프로그램 시작
값을 입력하셔야 합니다. //입력하는 값에 따라 다르게 출력됨
프로그램 종료
'JAVA' 카테고리의 다른 글
java.io패키지 기본 실습 (0) | 2013.02.05 |
---|---|
Exception 예외처리 기본 실습2 (0) | 2013.02.04 |
Arrays 클래스 실습 (0) | 2013.02.04 |
StringTokenizer 기본 실습 (0) | 2013.02.04 |
[실습]달력 출력 (0) | 2013.02.04 |