[모던C++입문] 1.6 예외 처리

짜장범벅·2022년 6월 4일
0

모던CPP입문

목록 보기
2/11

1.6 예외 처리

예외 처리에는 크게 두 방법이 있다.

1.6.1 Assertion

Assertion은 c의 헤더인 에 정의되어 있다. 표현식을 계산한 뒤 결과가 false면 프로그램을 즉시 종료한다. 예를 들어 제곱근(Square Root)를 구하는 함수를 다음과 같이 구현해보자

#include <iostream>
#include <cassert>
#include <math.h>

double sqrtWithAssert(double input)
{
        assert(input >= 0.0);

        //Below, input >= 0.
         double result = sqrt(input);

         return result;
}

int main(){

        while(true)
        {
                double x;
                std::cout << "input x : " << std::endl;
                std::cin >x;

                std::cout << "sqrt : " << sqrtWithAssert(x) << std::endl;
        }

        return 0;
}

당연히, sqrt를 하기 위해서는 양수를 입력해야하기 때문에 그 이전에 assert를 이용해 예외 처리를 해준다. 결과는 다음과 같다.

input x : 
5
sqrt : 2.23607
input x : 
4
sqrt : 2
input x : 
8
sqrt : 2.82843
input x : 
-2
Assertion_sqrt: Assertion_sqrt.cpp:7: double sqrtWithAssert(double): Assertion `input >= 0.0' failed.
중지됨 (core dumped)

Assert의 가장 큰 장점은 매크로 선언으로 비활성화를 한 번에 할 수 있다는 것이다. 만약 위의 코드를 Compile할 때, NDEBUG를 선언하면 Assertion은 비활성화가 된다.

즉,

g++ Assertion_sqrt.cpp -DNDEBUG

를 이용해 Compile하면 Assertion이 비활성화가 된다.

1.6.2 Exception

Try-Catch 문을 이용하면 예외 처리를 할 수 있다.

(생략)

profile
큰일날 사람

0개의 댓글