I know that exception should be thrown in exceptional case (e.g. out of memory, programmer error). For these cases, I don't need to worry about performance throwing these exception.
But what happen if use exception in normal code path?
In my case, use it to stop user code supplied function.
So for given code, is foo
better or foo2
better?
It is very likely that outputFunc
will return false / throw exception.
// library provided function
void foo(std::function<void(std::function<bool(int)>)>);
// how user suppose to use it
foo([](std::function<bool(int)> outputFunc){
while (/*condition*/)
{
// user have to check the return value and stop work when it return false
if (!outputFunc(/*some value*/)) return;
}
});
// library provided function
void foo2(std::function<void(std::function<void(int)>)>);
// how user suppose to use it
foo2([](std::function<void(int)> outputFunc){
while (/*condition*/)
{
// this will throw exception and handled internally when it should stop
// user does not have to check the return value but they need to write exception-safe code
outputFunc(/*some value*/));
}
});
In my case, the use of exception eliminate a possible programmer error (by not checking return value of outputFunc
) and make code easier to write (no need to check return value)
And the exception is throw/catch internally, no user code required to deal with them (except they need to write exception-safe code in the lambda, but we should always write exception-safe code)