C++ Exception


C++에서 예외 처리는 프로그램 실행 중 발생할 수 있는 예기치 않은 상황을 처리하는 중요한 기능입니다. 예외 처리를 위해 try, catch, throw 키워드를 사용하며, 표준 예외 클래스와 사용자 정의 예외 클래스를 구현할 수 있습니다. 아래에서 각 개념을 자세히 설명하겠습니다.

try, catch, throw 기본 구문

try 블록

try 블록은 예외가 발생할 수 있는 코드를 포함하는 블록입니다. 예외가 발생할 경우 이 블록 내에서 예외가 발생합니다.

#include <iostream>

int main() {
    try {
        // 예외가 발생할 수 있는 코드
        int numerator = 10;
        int denominator = 0;
        if (denominator == 0) {
            throw "나누는 수가 0입니다.";
        }
        int result = numerator / denominator;
        std::cout << "결과: " << result << std::endl;
    } catch (const char* msg) {
        std::cerr << "예외 발생: " << msg << std::endl;
    }

    return 0;
}

catch 블록

catch 블록은 try 블록에서 발생한 예외를 처리하는 블록입니다. 발생한 예외의 타입에 따라 적절한 catch 블록이 실행됩니다.

#include <iostream>

int main() {
    try {
        // 예외가 발생할 수 있는 코드
        int numerator = 10;
        int denominator = 0;
        if (denominator == 0) {
            throw "나누는 수가 0입니다.";
        }
        int result = numerator / denominator;
        std::cout << "결과: " << result << std::endl;
    } catch (const char* msg) {
        std::cerr << "예외 발생: " << msg << std::endl;
    }

    return 0;
}

throw 키워드

throw 키워드는 예외를 발생시키는 데 사용됩니다. throw 뒤에는 예외를 나타내는 값이나 객체가 옵니다.

#include <iostream>
#include <stdexcept>

int main() {
    try {
        int age;
        std::cout << "나이 입력: ";
        std::cin >> age;

        if (age < 0) {
            throw std::invalid_argument("나이는 음수일 수 없습니다.");
        }

        std::cout << "나이: " << age << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "예외 발생: " << e.what() << std::endl;
    }

    return 0;
}

표준 예외 클래스

C++에서는 표준 예외 클래스들이 <stdexcept> 헤더 파일에 정의되어 있습니다. 주요 표준 예외 클래스에는 다음과 같은 것들이 있습니다:

  • std::exception: 모든 표준 예외 클래스의 기본 클래스입니다.
  • std::invalid_argument: 잘못된 인수가 전달되었음을 나타내는 예외입니다.
  • std::runtime_error: 런타임 에러가 발생했음을 나타내는 예외입니다.

이 예외 클래스들은 필요한 경우 상속받아 사용자 정의 예외 클래스를 만들 수 있습니다.

사용자 정의 예외 클래스

사용자 정의 예외 클래스를 만들 때에는 표준 예외 클래스를 상속받아 구현합니다. 예를 들어, 특정 조건에서 예외를 발생시키고자 할 때 사용할 수 있습니다.

#include <iostream>
#include <stdexcept>

class MyException : public std::exception {
public:
    const char* what() const noexcept override {
        return "사용자 정의 예외 발생";
    }
};

int main() {
    try {
        throw MyException();
    } catch (const std::exception& e) {
        std::cerr << "예외 발생: " << e.what() << std::endl;
    }

    return 0;
}

예외 처리의 중요성

예외 처리는 프로그램의 안정성을 높이고 예기치 않은 상황에서도 적절하게 대응할 수 있도록 도와줍니다. 특히 파일 입출력, 네트워크 통신 등에서 발생할 수 있는 예외 상황을 미리 예측하여 처리할 수 있습니다.

위의 예제들을 통해 C++에서의 예외 처리의 기본적인 개념과 활용 방법을 이해할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *