반응형
Try Catch Finally
public class TryMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 예외처리
// java.lang.ArrayIndexOutOfBoundsException
// index의 범위를 벗어났다는 error.
// try catch finally 문법 : 예외를 처리하는 방법
// 예외가 발생했을때 내가 원하는 코드를 실행시키는 방법
int[] arr = {15, 2, 7};
try {
// 아래는 예외가 발생하는 코드이다. 배열은 index가 2까지 설정되어 있는데
// 4까지 기재했다.
// 이럴때 지금처럼 예외가 발생할 수 있는 경우는 try 안에 넣어준뒤
// catch를 통해 내가 원하는 코드처리를 해준다.
for( int i = 0; i < 4 ; i++ ) {
System.out.println(arr[i]);
}
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("배열 인덱스 예외 발생시 처리하는 코드 " + e.toString());
System.out.println(e.getMessage());
}catch(ArithmeticException e) {
System.out.println("연산 예외 발생시 처리하는 코드 ");
System.out.println(e.getMessage());
}catch(Exception e) {
System.out.println("나머지 모든 예외 발생시 여기서 처리 ");
System.out.println(e.getMessage());
}finally { // finally는 옵션이기때문에 있어도되고 없어도 된다.
System.out.println("예외가 발생하든 발생하지 안든 꼭 실행해야 하는 코드는 여기 작성");
}
}
}

반응형
'Language > JAVA' 카테고리의 다른 글
| JAVA - HashMap ( Iterator를 이용해 데이터 가져오기 ) (0) | 2022.07.06 |
|---|---|
| JAVA - ArrayList (0) | 2022.07.06 |
| JAVA - String Func (0) | 2022.07.06 |
| JAVA - Interface (0) | 2022.07.06 |
| JAVA - Abstract (추상클래스) (0) | 2022.07.06 |