Whats the right approach for error handling in C++

2019-01-22 22:51发布

One is to use C++ exceptions: try catch blocks. But freeing dynamic memory will be an issue when an exception is raised.

Second is to use C style: errno variable

Third is just to return -1 on error and 0 on success :)

Which way should be chosen for a mid-size project and why? Any other better approach..?

8条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-22 23:14

Second is to use C style: errno variable

Third is just to return -1 on error and 0 on success :)

And how do they help solving your problem of freeing dynamic memory? They also use an early-exit strategy, same as throw.

So in summary, they don’t have an advantage over C++ exceptions (according to you).

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-22 23:18

Have a look at this comment by Herb Sutter on try catch for C++ GOTW. And do go through his whole set of articles. He does have a lot to say on when and how to check and save yourself from error conditions and how to handle them in the best ways possible.

查看更多
登录 后发表回答