반응형
try에서 예외가 발생되면 → catch로 넘어가서 처리가 된다 → finally는 예외 상관없이 실행한다(생략가능)
package exception.prcatice;
public class ClassCastException {
public static void main(String[] args) {
String data1 = null;
String data2 = null;
try {
data1 = args[0];
data2 = args[1];
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("실행 매개값의 수가 부족합니다");
System.out.println("실행방법은");
System.out.println("java TryCatchFinallyRuntiomeException num1 num2");
return;
}
try {
int value1 = Integer.parseInt(data1);
int value2 = Integer.parseInt(data2);
int result = value1 + value2;
System.out.println(value1 +"+"+ value2 +"="+result);
}catch(NumberFormatException e){
System.out.println("숫자로 변환할 수 없습니다");
}finally {
System.out.println("다시 실행하세요");
}
}
}
**catch(~~~~~) 물결표시 부분에 '예외 에러 상태'를 넣음으로써 그 에러가 발생했을 때 실행할 수 있도록 만든다.
**catch의 멀티 작업은 catch(ArrayIndexOutOfBoundsException | NumberFormatException)으로 작성하면 된다
**Integer.paresXXX라는 것은 문자를 숫자로 변환하는 메소드 (instanceof는 변환 가능한지 알려주는 연산자)
첫번째 Catch 에서 ArrayIndexOUtOfBoundsException 예외는 배열 인덱스 범위를 초과하요 사용할 경우 예외로 발생되는 상태를 의미한다.
두번째 Catch의 NumberFormatException은 문자 데이터를 숫자로 변환하지 못한다는 예외상태
현재 첫번재 Catch 에서 오류가 발생하면서 console에는 이렇게 출력된다.
실행 매개값의 수가 부족합니다
실행방법은
java TryCatchFinallyRuntiomeException num1 num2
반응형
'IT 공부 > JAVA' 카테고리의 다른 글
| [코딩테스트] Lv1. 신고결과 받기 (0) | 2022.08.29 |
|---|---|
| [API]equals() (0) | 2021.01.15 |
| [예외]NumberFormatException (0) | 2021.01.12 |
| [예외]arrayIndexOutofBoundsException (0) | 2021.01.11 |
| [예외]NullPointerException (0) | 2021.01.11 |
댓글