티스토리 뷰
주요 클래스와 함수
1. std::exception
모든 표준 예외 클래스의 기본 클래스입니다. 예외 객체를 던질 때 catch 블록에서 예외를 포괄적으로 처리할 수 있도록 설계되었습니다. what() 메서드를 통해 예외와 관련된 설명을 반환합니다.
#include <iostream>
#include <exception>
int main() {
try {
throw std::exception(); // std::exception 예외 던짐
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
2. std::bad_alloc
- 동적 메모리 할당 실패 시 발생하는 예외 클래스.
- 예: new 연산자가 메모리 할당에 실패하면 이 예외가 발생
#include <iostream>
#include <exception>
int main() {
try {
int* arr = new int[1000000000000]; // 메모리 할당 실패
} catch (const std::bad_alloc& e) {
std::cout << "Caught bad_alloc: " << e.what() << std::endl;
}
return 0;
}
3. std::logic_error 및 파생 클래스
- 논리적인 오류를 나타내는 예외 클래스.
- 주요 파생 클래스:
- std::invalid_argument: 잘못된 인자가 전달되었을 때 사용.
- std::out_of_range: 컨테이너의 범위를 벗어나는 경우
#include <iostream>
#include <stdexcept>
int main() {
try {
throw std::out_of_range("Index out of range");
} catch (const std::out_of_range& e) {
std::cout << "Caught out_of_range: " << e.what() << std::endl;
}
return 0;
}
4. std::runtime_error 및 파생 클래스
- 런타임 오류를 나타내는 예외 클래스.
- 주요 파생 클래스:
- std::overflow_error: 산술 오버플로우 발생.
- std::underflow_error: 산술 언더플로우 발생.
#include <iostream>
#include <stdexcept>
int main() {
try {
throw std::overflow_error("Arithmetic overflow");
} catch (const std::overflow_error& e) {
std::cout << "Caught overflow_error: " << e.what() << std::endl;
}
return 0;
}
5. std::terminate
- 예외가 던져졌지만 잡히지 않을 경우 호출되는 함수.
- 디폴트로 프로그램을 종료합니다.
#include <iostream>
#include <exception>
void unexpectedHandler() {
std::cout << "Unexpected exception occurred!" << std::endl;
std::terminate();
}
int main() {
std::set_terminate(unexpectedHandler);
throw 42; // int 타입 예외 던짐 (잡히지 않음)
return 0;
}
6. std::current_exception 및 std::rethrow_exception
- 현재 활성화된 예외 객체를 포착하거나 다시 던질 때 사용.
사용 예제:
#include <iostream>
#include <exception>
void rethrow() {
try {
throw; // 현재 활성화된 예외 다시 던짐
} catch (const std::exception& e) {
std::cout << "Rethrown exception: " << e.what() << std::endl;
}
}
int main() {
try {
throw std::runtime_error("Original exception");
} catch (...) {
rethrow();
}
return 0;
}
'공부한거 > C++' 카테고리의 다른 글
#include<utility> (0) | 2024.11.22 |
---|---|
#include <string> (0) | 2024.11.21 |
#include <array> (0) | 2024.11.21 |
느낌대로 namespace 정의 (0) | 2024.11.21 |