异常处理(EH)似乎是当前的标准,通过搜索网络,我找不到任何新的想法或方法来改进或取代它(好吧,存在一些变化,但没有什么新奇的)。
尽管大多数人似乎忽略了它或只是接受它,EH有一些巨大的缺点:异常对代码是不可见的,它创建了许多许多可能的退出点。软件的Joel写了一篇关于它的文章。与goto的对比非常完美,这让我再次思考EH。
我尽量避免EH,只使用返回值,回调或任何符合目的的东西。但是,当您必须编写可靠的代码时,现在就不能忽略EH了:它从new开始,可能会抛出异常,而不只是返回0(就像以前一样)。这使得几乎每一行c++代码都容易出现异常。然后在c++基本代码中抛出异常的地方更多……STD lib可以这样做,等等。
这感觉就像在摇摇欲坠的地面上行走。因此,现在我们不得不关注异常!
但这很难,真的很难。你必须学会编写异常安全的代码,即使你有一些这方面的经验,仍然需要仔细检查每一行代码的安全性!或者您开始到处放置try/catch块,这会使代码变得混乱,直到达到不可读的状态。
EH replaced the old clean deterministical approach (return values..), which had just a few but understandable and easily solveable drawbacks with an approach that creates many possible exit points in your code, and if you start writing code that catches exceptions (what you are forced to do at some point), then it even creates a multitude of paths through your code (code in the catch blocks, think about a server program where you need logging facilities other than std::cerr ..). EH has advantages, but that's not the point.
我真正的问题是:
你真的写异常安全的代码吗? 您确定最后的“生产就绪”代码是异常安全的吗? 你能确定这是真的吗? 你知道和/或实际上使用有效的替代方法吗?