Skip to content

Don't Use Assert() If You Don't Mean It (C++)

December 26th, 2015 - Software(1 min)

I found the hard way that assert() in C/C++ exists hard. This post explains that you get a SIGABRT . So, if you want your code to be testable, you better throw an exception instead.

I defined a

LOGIC_ERROR(condition)

macro:

#define LOGIC_ERROR(e) if(!(e)) throw std::logic_error(#e)

So, in a code like this:

int function() {
    LOGIC_ERROR(1 > 2);
}

You’ll get an exception with the message “1 > 2”. Useful. You can use this sort of behaviour in e.g. unit tests (bonus: exceptions are good for you!)

Share on

A little experiment: