Boost logo

Boost :

Subject: Re: [boost] Exceptions vs Assertion for library API?
From: Stefan Seefeld (stefan_at_[hidden])
Date: 2017-11-11 02:08:38


On 10.11.2017 20:53, Jonathan Biggar via Boost wrote:
> Any advice in choosing between throwing an exception vs asserting for
> invalid uses of a library API?

Interesting question !

I'd strongly argue for assertions, against exceptions, in that case.

> I'm building a small "transactional" library I'd like to contribute to
> boost where certain API calls are constrained to only be valid if the
> transaction is still "in-progress". Such calls will never succeed, and are
> easy for the implementation to diagnose.

Now that is different: now the question is about behaviour, i.e. do you
want the library to report the error, or do you want to assume that the
input is valid ?
Assertions are useful if you allow different build variants, where a
"debug" variant can be used to validate application code against your
library, while a "release" variant simply assumes that the code uses
your library correctly. If you don't want to make that distinction, i.e.
always want to have a check, that would be an argument for exceptions.

> I'd like to have the library fail
> an assertion, which is far clearer to the user that the code logic is
> incorrect, but it bothers me that assertions are much more difficult to
> write unit tests for. (Is there even a concept of a test that passes if if
> fails to compile or fails with an assertion in the boost testing framework?)

Yes, if you want to test the assertion of preconditions and invariants,
you can certainly do that. Make sure that an invalid argument to a
function call has the expected result, i.e. either an exception or an
abort. Of course, you wouldn't be able to test that in-process (as the
process would abort), but with a robust testing framework you can catch
aborts as valid process outcomes.

Of course, testing for raised exceptions is even easier, as they don't
require you to run tests  in sub-processes.
> I suppose I could mangle the interface to ensure that the user has nothing
> to invoke the API calls in question unless the transaction is in-progress,
> but that generally requires a custom "lock" interface for my RAII
> implementation that makes the API more complex to grasp.

Regards,

Stefan

-- 
      ...ich hab' noch einen Koffer in Berlin...
    

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk