Search code examples
c++unit-testingabort

Is it possible to recover from std::abort?


Our C codebase is using assert to check that preconditions/post conditions are being met.

#include <cstdlib>
#include <cassert>

void Aborting_Function(int n);

int main(){

    Aborting_Function(1); //good
    Aborting_Function(0); //calls std::abort()

    //Is it possible to recover somehow?
    //And continue on...
}

void Aborting_Function(int n){
    assert(n > 0);
    //impl...
}

In unit testing, I want to verify that functions are properly following their contracts
(aborting when they should).

Is it possible to recover from std::abort?

I realize it seems somewhat repetitive to have unit tests check exactly same thing that the assertions should be checking, but this would be helpful as we could automate the checking of particular use cases that should not work.


Solution

  • Short answer, "no".

    Rather than subverting abort(), you may want to consider using the google test framework.

    This has the DEATH_TEST (documentation here: https://github.com/google/googletest/blob/master/googletest/docs/V1_7_AdvancedGuide.md)

    Essentially what this does is fork a child process and checks whether the statement causes it to exit (which it would do if it aborted).