Learn & Record

[코리아IT아카데미] JAVA - Exception (예외) 본문

Dev/Java

[코리아IT아카데미] JAVA - Exception (예외)

Walker_ 2024. 2. 2. 13:44

1. Exception (예외)

 - 어떤 프로그램이든, 잘못된 코드, 부정확한 데이터, 예외적인 상황으로 오류가 발생할 수 있음

 - 프로그램 비정상 종료를 막고, 정상 실행 상태를 유지하는 것이 목적

 

2. try-catch 구조

 - 자바에서는 try-catch 구조를 사용해서 예외를 처리

 - 예외마다 하나의 catch 블록을 지정하여야 함

 - 예외가 발생할 가능성이 있는 코드를 try 블록으로 감싸고 처리 과정은 catch 블록에 위치시키면 됨

try {
	# 예외가 발생할 수 있는 코드
} catch (예외클래스 변수) {
	# 예외를 처리하는 코드
} finally {
	# 여기 있는 코드는 try 블록이 끝나면 무조건 실행
}
public class DivideMyZeroOK {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // 예외 발생!
        } catch (ArithmeticException e) {
            System.out.println("0으로 나눌 수 없습니다.");
        }
        System.out.println("프로그램은 계속 진행됩니다.");
    }
}

 

3. try-with-resource

 - JAVA 7에서 도입된 새로운 예외 처리 메커니즘 사용되는 리소스를 자동으로 닫음.

 - try 키워드 바로 다음에 소괄호가 있으면 리소스로 취급

public class MyException06_2 {
    public static void main(String[] args) {
        // fubally를 사용하는 예
        String path = ".\\sample_file\\test.txt";

        try (FileInputStream fileInputStream = new FileInputStream(path)){
            System.out.println("지정한 경로에 파일이 존재합니다.");
        } catch (FileNotFoundException e) {
            System.out.println("지정한 경로에 파일이 존재하지 않습니다.");
        } catch (IOException e){
            throw new RuntimeException(e);
        }
    }
}

 

4. 연습문제 

public class Ex_01 {
	# 비정상 종료를 하는데, try ~ catch를 이용해서 
    # 예외를 안전하게 처리하도록 코들르 수정할 것
    public static void main(String[] args) {
        int[] arr = new int[10];

        for(int i = 0; i < 10; i++) {
            arr[i] = i;
        }
        for (int i = 0; i < 11; i++) {
             System.out.println(arr[i]);
        }       
    }
}
    public static void main(String[] args) {
        int[] arr = new int[10];

        for(int i = 0; i < 10; i++) {
            arr[i] = i;
        }
        try {
            for (int i = 0; i < 11; i++) {  //예외 발생 코드
                System.out.println(arr[i]);
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("배열에 없는 index는 출력이 안됩니다."); // 예외 발생 시 실행 코드
        }
        System.out.println("프로그램은 계속 진행됩니다."); // 무조건 실행 코드
    }
}