선언 & 사용
try{
throw 예외 값
}catch(예외_형식 예외_이름){
}
#include <iostream>
using namespace std;
int main() {
try {
int input;
cout << "정수 중 하나를 입력하세요 : ";
cin >> input;
if (input > 0) {
cout << "throw 1" << endl;
throw 1;
cout << "after throw 1" << endl;
}
if (input < 0) {
cout << "throw -1.0f" << endl;
throw - 1.0f;
cout << "after throw -1.0f" << endl;
}
if (input == 0) {
cout << "throw z" << endl;
throw "z";
cout << "after throw z" << endl;
}
}
catch (int a) {
cout << "catch " << a << endl;
}
catch (float b) {
cout << "catch " << b << endl;
}
catch (char c) {
cout << "catch " << c << endl;
}
catch (...) {
cout << "catch all" << endl;
}
return 0;
}
스택 풀기
- func 함수에서 던진 예외가 함수를 호출한 main영역의 catch에서 정상으로 처리됨 -> 예외 처리의 책임은 throw가 발생한 함수를 호출한 쪽으로 넘어감
#include <iostream>
using namespace std;
int fun(){
throw -1;
}
int main(){
try {
fun();
}catch(int exec){
cout << catch " << exec << endl;
}
return 0;
}
어설션
- 예상치 못한 상황에서 프로그램 동작을 중단 시키는 도구
- 디버그 모드에서만 컴파일 됨 -> 다른 코드에 영향을 주지 않는 코드로만 작성해야 함
#include <iostream>
#include <cassert>
using namespace std;
void printNumber(int *ptr){
assert(ptr != NULL);
cout << *ptr << endl;
}
int main(){
int a = 100;
int *b = NULL;
int *c = NULL;
b = &a;
printNumber(b);
printNumber(c);
return 0;
}

noexcept
int fun() noexcept
bool f - noexcept(fun());
예외 처리 실패 대응
- throw 예외 던졌는데 catch없거나 형식이 안맞으면 프로그램 종료됨
- set_terminate로 강제 종료되기 전에 특정 동작 수행하도록 구성할 수 있음
#include <iosream>
#include <cstdlib>
using namespace std;
void myterminate(){
cout << "myterminate called" << endl;
exit(-1);
}
int main(){
set_terminate(myterminate);
throw 1;
return 0;
}