개요
- 예외가 발생하지 않는 함수에 정의
void func5() noexcept {}
- 해당 함수에서 예외 발생 시 catch 되지 않고 크러쉬
예제
- 코드
#include <iostream>
#include <string>
using namespace std;
void func1();
void func2();
void func3();
class Test {
private:
int i;
public:
Test(int i) : i(i) {}
~Test() { cout << "~Test() - " << this->i << endl; }
void func(){};
};
void func1() {
cout << "func1() start" << endl;
func2();
cout << "func1() end" << endl;
}
void func2() {
cout << "func2() start" << endl;
func3();
cout << "func2() end" << endl;
}
void func3() {
cout << "func3() start" << endl;
Test t1(1);
Test *t2 = new Test(2);
t2->func();
throw out_of_range("aaa");
cout << "func3() end" << endl;
}
void func4(const int &i) {
switch (i) {
case 1:
throw 1;
case 2:
throw 'c';
case 3:
throw "aaa";
case 4:
throw string("bbb");
default:
throw out_of_range("ccc");
}
}
void func5() noexcept {}
int main() {
try {
func1();
cout << "func() after" << endl;
} catch (out_of_range &e) {
cout << e.what() << endl;
}
try {
func4(1);
} catch (int &i) {
cout << "i : " << i << endl;
} catch (char &c) {
cout << "c : " << c << endl;
} catch (const char *pc) {
cout << "pc : " << pc << endl;
} catch (string &s) {
cout << "s : " << s << endl;
} catch (...) {
cout << "other catch" << endl;
}
func5();
cout << "main end" << endl;
return 0;
}
- 실행 결과
func1() start
func2() start
func3() start
~Test() - 1
aaa
i : 1
main end