ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • C++ std::exception 을 사용하는 방법
    프로그래밍 언어/C/C++ 2025. 9. 16. 22:07
    반응형

    C++에서 std::exception 기반 예외 처리 예제 모음

    C++에서는 표준 예외 클래스 std::exception 및 이를 상속한 다양한 예외 클래스를 사용하여 예외를 정의하고 처리할 수 있습니다.


    1. 기본 std::exception 사용 예제

    #include <iostream>
    #include <exception>
    
    int main() {
        try {
            throw std::exception();
        } catch (const std::exception& e) {
            std::cerr << "Caught exception: " << e.what() << '\n';  // 출력: std::exception
        }
        return 0;
    }

    2. std::runtime_error 사용 예제

    #include <iostream>
    #include <stdexcept>
    
    int main() {
        try {
            throw std::runtime_error("Something went wrong!");
        } catch (const std::runtime_error& e) {
            std::cerr << "Runtime error: " << e.what() << '\n';
        }
    }

    3. 사용자 정의 예외 클래스

    #include <iostream>
    #include <exception>
    #include <string>
    
    class MyException : public std::exception {
        std::string message;
    public:
        MyException(const std::string& msg) : message(msg) {}
        const char* what() const noexcept override {
            return message.c_str();
        }
    };
    
    int main() {
        try {
            throw MyException("Custom exception thrown!");
        } catch (const std::exception& e) {
            std::cerr << "Caught: " << e.what() << '\n';
        }
    }

    4. std::out_of_range 예제

    #include <iostream>
    #include <vector>
    #include <stdexcept>
    
    int main() {
        std::vector<int> v = {1, 2, 3};
        try {
            std::cout << v.at(5) << '\n';  // 범위 벗어남
        } catch (const std::out_of_range& e) {
            std::cerr << "Out of range: " << e.what() << '\n';
        }
    }

    5. std::invalid_argument 예제

    #include <iostream>
    #include <stdexcept>
    
    int divide(int a, int b) {
        if (b == 0) throw std::invalid_argument("Division by zero");
        return a / b;
    }
    
    int main() {
        try {
            std::cout << divide(10, 0);
        } catch (const std::invalid_argument& e) {
            std::cerr << "Invalid argument: " << e.what() << '\n';
        }
    }

    6. 예외 클래스 중첩 처리 예제

    #include <iostream>
    #include <stdexcept>
    
    int main() {
        try {
            try {
                throw std::invalid_argument("Inner exception");
            } catch (...) {
                std::throw_with_nested(std::runtime_error("Outer exception"));
            }
        } catch (const std::exception& e) {
            std::cerr << "Caught: " << e.what() << '\n';
            try {
                std::rethrow_if_nested(e);
            } catch (const std::exception& inner) {
                std::cerr << "Nested: " << inner.what() << '\n';
            }
        }
    }

    7. noexcept 와 예외 간의 관계

    void willNotThrow() noexcept {
        throw std::runtime_error("Oops");  // std::terminate 호출됨
    }
    
    int main() {
        try {
            willNotThrow();
        } catch (...) {
            std::cerr << "You won't reach here\n";
        }
    }

    noexcept 함수 내에서 예외가 발생하면 std::terminate()가 호출되므로 주의해야 합니다.


    8. 예외를 사용한 간단한 파일 처리

    #include <iostream>
    #include <fstream>
    #include <stdexcept>
    
    void readFile(const std::string& path) {
        std::ifstream file(path);
        if (!file.is_open()) {
            throw std::runtime_error("Cannot open file: " + path);
        }
    }
    
    int main() {
        try {
            readFile("nonexistent.txt");
        } catch (const std::exception& e) {
            std::cerr << "File error: " << e.what() << '\n';
        }
    }

    참고: 주요 표준 예외 클래스 목록

    예외 클래스 설명
    std::exception 모든 표준 예외의 기본 클래스
    std::runtime_error 런타임 오류
    std::logic_error 논리 오류
    std::out_of_range 컨테이너 인덱스 초과
    std::invalid_argument 유효하지 않은 인자
    std::length_error 길이 초과 오류
    std::bad_alloc 메모리 할당 실패
    std::bad_cast 잘못된 형변환
    반응형

    댓글

Designed by Tistory.