// education

제어문과 반복문 및 배열(Array)과 예외 처리

프로그램의 논리 실행 흐름을 통제하는 조건문/반복문과 여러 데이터를 묶어 관리하는 배열(Array), 런타임 오류에 대비하는 **예외 처리(Exception Handling)**를 익힙니다.


1. 제어문 & 예외 처리 용어 사전 (Glossary)


2. 배열과 향상된 for문 활용 예제

public class ArrayExample {
    public static void main(String[] args) {
        // 정수형 배열 선언 및 초기화
        int[] scores = {90, 85, 95, 100, 78};
        int sum = 0;

        // 향상된 for문 (Enhanced for-loop) 순회
        for (int score : scores) {
            sum += score;
        }

        double average = (double) sum / scores.length;
        System.out.println("성적 합계: " + sum + "점");
        System.out.printf("성적 평균: %.2f점
", average);
    }
}

3. try-catch-finally 예외 처리 실전 가이드

public class ExceptionExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30};

        try {
            System.out.println("배열 요소 읽기: " + numbers[5]); // IndexOutOfBoundsException 발생!
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("경고: 존재하지 않는 배열 인덱스에 접근했습니다!");
            System.err.println("에러 메시지: " + e.getMessage());
        } finally {
            // 예외 발생 여부와 상관없이 항상 마무리를 위해 실행되는 구역
            System.out.println("안전하게 예외 처리 구문이 종료되었습니다.");
        }
    }
}

4. 자주 묻는 질문 (Q&A)

Q. Checked Exception과 Unchecked Exception의 차이는 무엇인가요? A. Checked Exception(예: IOException, SQLException)은 반드시 코드상에서 try-catch나 throws로 예외 처리를 해야만 컴파일이 되며, Unchecked Exception(RuntimeException 상속 클래스들)은 개발자의 주의로 회피 가능한 예외로 컴파일러가 강제하지 않습니다.

← 이전변수, 기본 자료형 및 연산자 완벽 해설 다음 →객체지향 프로그래밍 기초: 클래스, 객체, 메소드