[모던C++입문] 1.6 오류 처리
- 📕 Book/모던C++입문
- 2021. 7. 3.
1.6 오류 처리
단정
- cassert의 매크로 assert는 표현식을 계산 후 결과가 false이면 프로그램을 종료한다
#include <cassert>
double square_root(double x)
{
check_somhow(x >= 0);
//중략
assert(result >= 0.0);
return result;
}
assert의 결과가 false라면 다음과 같은 오류를 출력
assert_test : assert_test.cpp:10: double square_root(double);
Assertion : 'result >= 0.0' failed.
예외
동기 부여
- 오류 코드를 반환하는 방식
int read_matrix_file(const char* fname, ...)
{
fstream f(fname)
if(!f.is_open())
return 1;
//중략
return 0;
}
던지기
struct cannot_open_file {};
void read_matrix_file(const char* fname, ...)
{
fstream f(fname);
if(!f.is_open())
throw cannot_open_file {};
//후략
}
잡기
- try-catch 블록으로 예외를 붙잡을 수 있다
try{
read_matrix_file("does_not_exist.dat");
} catch (cannot_open_file& e) {
cerr << "omg, the file is not there" << endl;
throw e; //예외를 다시 던짐
}
//catch (cannot_open_file& e) {} //빈블록을 사용하면 예외를 무시
bool keep_trying = true;
do{
cout << "enter the file name :";
cin >> fname;
try{
read_matrix_file(fname);
...
keep_trying = false;
} catch (cannot_open_file& e) {
cout << "could not open file. try another one" << endl;
} catch (...) {
cout << "something is fishy here." << endl;
}
} while(keep_trying);
던지지 않기
- noexcept는 예외를 확인하지 않아도 된다는 지정자 이다.
- 예외가 발생하면 프로그램을 종료한다.
정적 단정
- 컴파일 과정에서의 프로그램 오류는 static_assert를 발생시킬 수 있다
반응형