我知道异常情况下应该抛出异常(例如内存不足、程序员错误)。对于这些情况,我不需要担心抛出这些异常的性能。
但是,如果在正常代码路径中使用异常会发生什么呢?
在我的例子中,使用它来停止用户代码提供的函数。
因此,对于给定的代码,foo更好还是foo2更好?
outputFunc很可能会返回false /抛出异常。
// 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*/));
}
});在我的例子中,使用异常消除了一个可能的程序员错误(通过不检查outputFunc的返回值)并使代码更容易编写(不需要检查返回值)。
而且例外情况是内部抛出/捕获,不需要处理它们的用户代码(除非他们需要在lambda中编写异常安全代码,但我们应该始终编写异常安全代码)。
发布于 2014-05-04 03:04:38
如果一个函数不能完成它应该做的事情,并且返回一个值将是误导的,那么抛出异常似乎是唯一的其他选项。
这种情况在理想情况下永远不会发生,如果发生这种情况,它应该代表系统环境中的问题或代码中的错误。理想情况下,你应该尝试通过自己做一些预先验证来解决这个问题。例如,调用一些函数来检查输入/状态对于您真正想要调用的函数是否有效。该验证函数将返回一个布尔值,根据结果,您将知道是否调用预期的函数。
https://softwareengineering.stackexchange.com/questions/237843
复制相似问题