8

I am trying to understand how to use Ensures() in code. As given in the example, if I tried using Ensures() as follows...

int main(void)
{
    int result = 0;
    // Some calculation
    Ensures(result == 255);
    return 0;
}

If the result variable is not equal to 255, the program crashes with the following output "terminate called without an active exception". My question is how to use Ensures() properly?

NJMR
  • 1,886
  • 1
  • 27
  • 46

1 Answers1

14

Are you using the Microsoft GSL implementation? Then if you check the gsl_assert.h header file you will see that if GSL_TERMINATE_ON_CONTRACT_VIOLATION is defined (which is default) then Ensures will call std::terminate which will give you the error you get.

If you want an exception to be thrown (with file and line-number information) then you need to define GSL_THROW_ON_CONTRACT_VIOLATION before including the GSL.

As for if you're using Ensures properly, then yes you are.


Updates on 2021

GSL_TERMINATE_ON_CONTRACT_VIOLATION is removed, always calling terminate().

김선달
  • 1,485
  • 9
  • 23
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks, for the reply, will check the header. – NJMR Apr 01 '16 at 06:50
  • I am not using MS GSL. I tried using MS GSL with Visual Studio 2013. But was getting "fatal error C1001: An internal error has occurred in the compiler". – NJMR Apr 01 '16 at 06:52
  • As per your suggestion, I went into the "gsl-lite.h" and modified the # define gsl_CONFIG_THROWS_FOR_TESTING 0 to # define gsl_CONFIG_THROWS_FOR_TESTING 1. Now I am getting exception which i can catch it. Thanks. – NJMR Apr 01 '16 at 06:56
  • 3
    As decided by the Core Guideline authors the MS GSL lately removed `GSL_THROW_ON_CONTRACT_VIOLATION` and now always `std::terminate`s. But... there is still a discussion ongoing because the Core Guidelines seem to be inconsistent about the behaviour of `Expects`. – Werner Henze Feb 28 '20 at 17:02