반응형
std::exception
<exception>라이브러리
exception 클래스
자식으로 여러 클래스를 가지고 있다.
std::exception::what()함수를 통해 예외 상황을 알 수 있다.다음과 같이
exception클래스에서는 가상함수로 정의되어있다._NODISCARD virtual char const* what() const { return _Data._What ? _Data._What : "Unknown exception"; }https://en.cppreference.com/w/cpp/error/length_error 에 상속 다이어그램이 있으니 참고하면 좋다.
#include <iostream> #include <exception> using namespace std; int main() { try { string s; s.resize(-1); } catch (std::exception & exception) { cout << typeid(exception).name() << endl; cerr << exception.what() << endl; } } /* stdout stderr class std::length_error string too long */직접 자식 클래스를 던질 수도 있다.
#include <iostream> #include <exception> using namespace std; int main() { try { throw std::runtime_error("Bad thing happened"); } catch (std::exception & exception) { cout << typeid(exception).name() << endl; cerr << exception.what() << endl; } } /* stdout stderr class std::runtime_error Bad thing happened */
직접 상속받는 클래스 만들기
std::exception클래스를 상속받아 새로운 클래스를 정의하고 이를 사용할 수 있다.what함수를 오버라이딩해야 의미가 있다.noexceptC++11
예외를 던지지 않는다는 뜻이다. 없어도 되는 것 같다.
#include <iostream> #include <exception> using namespace std; class CustomException : public std::exception { public: const char* what() const noexcept override { return "Custom exception"; } }; int main() { try { throw CustomException(); } catch (std::exception & exception) { cout << typeid(exception).name() << endl; cerr << exception.what() << endl; } } /* stdout stderr class CustomException Custom exception */
반응형
'SW개발 > C++' 카테고리의 다른 글
| C++ 예외 처리의 위험성과 단점 (0) | 2021.03.22 |
|---|---|
| C++ 함수 try (Function try) (0) | 2021.03.22 |
| C++ 예외 클래스와 상속 (Exception Class and Inheritance) (0) | 2021.03.22 |
| C++ 스택 되감기 (Stack Unwinding) (0) | 2021.03.22 |
| C++ 예외 처리의 기본 (0) | 2021.03.22 |