Java - 예외 처리 - Try/Catch/Finally

반응형

예외 처리

  • 자바에서 문법적 오류나 논리적 오류가 발생 할 경우, 해당 예외를 처리하는 구문
  • 오류가 발생 할 것 같은 부분에서 Try로 정의
  • 오류가 발생 할 경우 수행 할 코드를 Catch로 정의

 

Try/Catch를 이용한 예외 처리 예시

int[] arr = {1, 2, 3};

try { // 오류가 발생 할 것 같은 부분에 정의
    for (int i=0; i<4; i++) { // 배열의 범위 초과
        System.out.println( arr[i] );
    }
}
catch (Exception e) { // 오류가 발생하면 수행 할 코드 정의
    System.out.println("오류 발생 : ");
}
// 오류 발생 : java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

예외 객체

  • 예외 객체를 이용하여 상황에 따른 대처
  • 예외 처리로 반환되는 오류의 이름을 적어주면 해당 오류 발생시 수행 코드 정의 가능
int[] arr = {1, 2, 3};

try {
    for (int i=0; i<4; i++) {
        System.out.println( arr[i] );
    }
}
catch (ArrayIndexOutOfBoundsException ArrayError) {
    System.out.println("배열 오류 : " + ArrayError);
}
catch (Exception e) {
    System.out.println("오류 발생 : " + e);
}
// 배열 오류 : java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

Finally

  • 예외 처리의 유무 상관없이 반드시 수행 할 코드를 정의

 

오류가 발생되는 예외 처리 구문

int[] arr = {1, 2, 3};

try {
    for (int i=0; i<4; i++) { // 배열 범위 초과로 오류 발생
        System.out.println( arr[i] );
    }
}
catch (Exception e) {
    System.out.println("오류 발생 : " + e);
}
finally {
    System.out.println("오류 발생 유무 상관없이 반드시 수행된다.");
}
// 오류 발생 : java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
// 오류 발생 유무 상관없이 반드시 수행된다.

 

오류가 발생되지 않는 예외 처리 구문

int[] arr = {1, 2, 3};

try {
    for (int i=0; i<3; i++) { // 배열 범위 정상적으로 입력, 오류 발생하지 않음
        System.out.println( arr[i] );
    }
}
catch (Exception e) {
    System.out.println("오류 발생 : " + e);
}
finally {
    System.out.println("오류 발생 유무 상관없이 반드시 수행된다.");
}
// 123
// 오류 발생 유무 상관없이 반드시 수행된다.
반응형