728x90
반응형
std::exception (예외 클래스)
여태까지 조건문을 이용하여 예외 상황임을 판단하여 직접 throw로 예외를 던졌었습니다.
std::exception 클래스를 통해 시스템 상 내부에서 알아서 발생한 예외를 throw 해줍니다.
std::exception은 CPP의 표준 클래스로 여러 종류의 예외를 나타내는 자식 클래스들을 가지고 있습니다.
다음과 같이 벡터 클래스의 길이보다 1 더 큰 크기를 재할당시켜 에러가 나도록 유도해봅시다.
#include <iostream>
#include <vector>
#include <exception>
using namespace std;
int main() {
try {
vector<int> v;
v.resize(v.max_size()+1);
}
catch(std::exception & e) {
cout << e.what() << endl;
}
}
여태까지는 조건문을 활용하여 잘못된 상황일 때 throw로 예외를 전달하여 해당하는 자료형으로 받도록 했는데 catch 를 exception 클래스를 하도록 하여 벡터를 최대 크기로 재할당 시켜 (v.resize(v.max_size()+1);) 발생한 예외를 catch하도록 합니다.
what 함수
위의 작성한 코드에는 예외가 발생하면 다음과 같은 구문을 사용하는 것을 볼 수 있습니다.
catch(std::exception & e) {
cout << e.what() << endl;
}
what이라는 함수가 호출되는 것을 볼 수 있는데 what이 대체 무엇일까요?
what 함수는 발생한 정의된 예외 종류의 원인 메시지를 반환하는 함수입니다.
what은 const char * 를 반환하며 이며, std::exception 클래스의 모든 자식 클래스는 가상 함수 what을 오버라이딩합니다.
나만의 커스텀 예외 만들어보기
exception 클래스를 상속받아 사용자 정의 예외 클래스를 만들어봅시다.
#include <iostream>
#include <vector>
#include <exception>
using namespace std;
class ftException : public std::exception {
public :
const char *what() const throw() {
return "my custom error";
}
};
int main() {
try {
throw ftException();
}
catch(std::exception & e) {
cout << e.what() << endl;
}
}
exception 에러 클래스가 잘 동작하는 것을 확인할 수 있습니다.
반응형
'CPP' 카테고리의 다른 글
CPP Standard Template Library - iterator (0) | 2021.12.11 |
---|---|
CPP Template (0) | 2021.12.09 |
CPP Casts (0) | 2021.12.04 |
CPP Exception - 2 (0) | 2021.11.28 |
CPP Exception - 1 (0) | 2021.11.27 |