자바

자바 예외 처리

thebasics 2024. 8. 21. 17:00

목차
1. 예외 처리란 무엇인가?
2. 예외의 종류
3. try-catch 문
4. 여러 개의 catch 블록
5. finally 블록
6. 예외 발생시키기
7. 사용자 정의 예외
8. 예제와 분석
9. 결론 및 추가 학습 자료


1. 예외 처리란 무엇인가?

예외 처리(Exception Handling)는 프로그램 실행 중 발생할 수 있는 예외적인 상황(오류)을 관리하는 방법입니다. 예외 처리를 통해 프로그램의 비정상 종료를 방지하고, 오류 발생 시 적절한 조치를 취할 수 있습니다. 자바에서는 try-catch 문을 사용하여 예외를 처리합니다.


2. 예외의 종류

자바에서 예외는 크게 두 가지로 나뉩니다:

1. 검사 예외 (Checked Exception): 컴파일 시점에서 체크되는 예외로, 반드시 예외 처리를 해야 합니다. 예: IOException, SQLException
2. 비검사 예외 (Unchecked Exception): 런타임 시점에서 발생하는 예외로, 예외 처리를 강제하지 않습니다. 예: NullPointerException, ArrayIndexOutOfBoundsException


3. try-catch 문

try-catch 문은 예외를 처리하기 위한 기본 구조입니다. 예외가 발생할 가능성이 있는 코드를 try 블록에 작성하고, 예외가 발생했을 때의 처리를 catch 블록에 작성합니다.

try-catch 문 구문:

try {
    // 예외가 발생할 가능성이 있는 코드
} catch (예외타입 변수이름) {
    // 예외 처리 코드
}

예제:

public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[3]); // 예외 발생
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds: " + e.getMessage());
        }
    }
}

설명:
- 'try' 블록에서 배열의 인덱스가 범위를 벗어나서 'ArrayIndexOutOfBoundsException' 예외가 발생합니다.
- 'catch' 블록에서 예외를 처리하고, 예외 메시지를 출력합니다.


4. 여러 개의 catch 블록

여러 개의 catch 블록을 사용하여 다양한 예외를 처리할 수 있습니다. 각 catch 블록은 특정 예외 타입을 처리합니다.

여러 개의 catch 블록 구문:

try {
    // 예외가 발생할 가능성이 있는 코드
} catch (예외타입1 변수이름1) {
    // 예외 타입1 처리 코드
} catch (예외타입2 변수이름2) {
    // 예외 타입2 처리 코드
}

예제:

public class MultipleCatchExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[3]); // 예외 발생
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("An unexpected error occurred: " + e.getMessage());
        }
    }
}

설명:
- 첫 번째 'catch' 블록은 'ArrayIndexOutOfBoundsException' 예외를 처리합니다.
- 두 번째 'catch' 블록은 그 외 모든 예외를 처리합니다.


5. finally 블록

finally 블록은 예외 발생 여부와 상관없이 항상 실행되는 코드 블록입니다. 주로 자원을 해제하거나 정리 작업을 수행하는 데 사용됩니다.

finally 블록 구문:

try {
    // 예외가 발생할 가능성이 있는 코드
} catch (예외타입 변수이름) {
    // 예외 처리 코드
} finally {
    // 항상 실행되는 코드
}

예제:

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[3]); // 예외 발생
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds: " + e.getMessage());
        } finally {
            System.out.println("This will always be executed");
        }
    }
}

설명:
- 'try' 블록에서 예외가 발생하더라도 'finally' 블록이 항상 실행됩니다.


 6. 예외 발생시키기

'throw' 키워드를 사용하여 명시적으로 예외를 발생시킬 수 있습니다. 이는 사용자 정의 예외를 만들거나 특정 조건에서 예외를 발생시키는 데 유용합니다.

예외 발생 구문:

if (조건) {
    throw new 예외타입("예외 메시지");
}

예제:

public class ThrowExample {
    public static void main(String[] args) {
        try {
            checkAge(15);
        } catch (Exception e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }

    static void checkAge(int age) throws Exception {
        if (age < 18) {
            throw new Exception("Age must be 18 or older");
        }
    }
}

설명:
- 'checkAge' 메서드에서 나이가 18 미만일 경우 'Exception' 예외를 발생시킵니다.
- 'main' 메서드에서 'checkAge' 메서드를 호출하고, 예외를 처리합니다.


7. 사용자 정의 예외

사용자 정의 예외는 표준 예외 클래스(Exception)를 상속받아 새로운 예외 클래스를 정의하는 것입니다.

사용자 정의 예외 클래스 구문:

public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

예제:

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            checkAge(15);
        } catch (CustomException e) {
            System.out.println("CustomException caught: " + e.getMessage());
        }
    }

    static void checkAge(int age) throws CustomException {
        if (age < 18) {
            throw new CustomException("Age must be 18 or older");
        }
    }
}

// 사용자 정의 예외 클래스
public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

설명:
- 'CustomException' 클래스는 사용자 정의 예외를 정의합니다.
- 'checkAge' 메서드는 나이가 18 미만일 경우 'CustomException' 예외를 발생시킵니다.
- 'main' 메서드에서 'checkAge' 메서드를 호출하고, 사용자 정의 예외를 처리합니다.


8. 예제와 분석

다양한 예외 처리 작업을 종합적으로 다루는 예제를 살펴보겠습니다.

종합 예제:

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            // 배열 인덱스 예외 발생
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[3]);

            // 명시적 예외 발생
            checkAge(15);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds: " + e.getMessage());
        } catch (CustomException e) {
            System.out.println("CustomException caught: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("An unexpected error occurred: " + e.getMessage());
        } finally {
            System.out.println("This will always be executed");
        }
    }

    static void checkAge(int age) throws CustomException {
        if (age < 18) {
            throw new CustomException("Age must be 18 or older");
        }
    }
}

// 사용자 정의 예외 클래스
public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

코드 분석:

- 'ArrayIndexOutOfBoundsException' 예외를 처리하여 배열 인덱스가 범위를 벗어날 때 발생하는 예외를 처리합니다.
- 'CustomException' 예외를 처리하여 사용자 정의 예외를 처리합니다.
- 'Exception' 예외를 처리하여 그 외 모든 예외를 처리합니다.
- 'finally' 블록을 사용하여 예외 발생 여부와 상관없이 항상 실행되는 코드를 작성합니다.


9. 결론 및 추가 학습 자료

이번 글에서는 자바의 예외 처리 방법에 대해 살펴보았습니다. 예외 처리는 프로그램의 비정상 종료를 방지하고, 오류 발생 시 적절한 조치를 취할 수 있도록 도와줍니다. try-catch 문을 사용하여 예외를 처리하고, 여러 개의 catch 블록을 사용하여 다양한 예외를 처리할 수 있습니다. 또한, finally 블록을 사용하여 항상 실행되는 코드를 작성하고, throw 키워드를 사용하여 명시적으로 예외를 발생시킬 수 있습니다. 사용자 정의 예외를 통해 프로그램에 맞는 예외를 정의하고 처리할 수도 있습니다. 예외 처리에 대한 이해를 바탕으로 자바 프로그래밍의 기본기를 탄탄히 다질 수 있습니다. 다음은 추가 학습 자료입니다:

추가 학습 자료:
- 자바 공식 문서: [Oracle Java Documentation](https://docs.oracle.com/javase/tutorial/essential/exceptions/)
- 온라인 자바 튜토리얼: [W3Schools Java Exceptions](https://www.w3schools.com/java/java_exceptions.asp)
- 자바 코딩 연습 사이트: [GeeksforGeeks](https://www.geeksforgeeks.org/100-days-of-java/)

자바는 강력한 기능을 가진 프로그래밍 언어로, 꾸준히 학습하면 다양한 응용 프로그램을 개발할 수 있습니다. 이번 기회를 통해 자바의 예외 처리를 잘 이해하고 더 나아가 복잡한 프로그래밍을 익히길 바랍니다.


이제 자바의 예외 처리에 대해 자세히 이해하게 되었습니다. 다음 글에서는 자바의 컬렉션 프레임워크에 대해 다루도록 하겠습니다. 자바의 더 깊은 이해를 위해 계속해서 학습해나가세요!

반응형

'자바' 카테고리의 다른 글

자바 제네릭  (0) 2024.08.23
자바 컬렉션 프레임워크  (0) 2024.08.22
자바 인터페이스  (0) 2024.08.20
자바 클래스와 객체  (0) 2024.08.19
자바 메서드  (0) 2024.08.18