-
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잘못된 형변환 반응형'프로그래밍 언어 > C/C++' 카테고리의 다른 글
C++ 타입 캐스팅(Type Casting) 연산자 종류 (1) 2025.09.17 🧰 C++11 std::atomic 표준 라이브러리 (0) 2023.06.01 🖥️ C++에서 윈도우 프로그램 동시 실행 방지하기 (0) 2023.02.28 C++20 코루틴 기능을 활용한 비동기 프로그래밍 예제 (0) 2023.02.23 C++ std::thread와 std::mutex를 사용한 멀티스레딩 예제 (0) 2023.02.22