C++ Exception Handling
A while ago I made a passing remark on my blog that I prefer not to use exceptions in native code. Some readers asked me to justify this position and I’ve been a bit reluctant to do so only because it’s a lengthy argument that I’m sure will bring a lot of passionate responses that I don’t really have the time to deal with. I was reminded of this again last night when I walked past one of our bookshelves at home and picked up my copy of John Robbins’ excellent debugging book and noticed that it has a chapter on crash handlers within which John does a good job of covering many of the reasons why I don’t use exception handling in native code. If you’re interested in this topic I would encourage you to read John’s book.
Of course I still write “exception safe” code in the sense that I use “resource acquisition is initialization” or constructors and destructors to scope resources, avoid side effects in functions, define invariants, etc. but this is just good practice to write simple and correct code whether or not exceptions are in play.
The Visual C++ compiler actually lets you disable exception handling in your code which by the way improves performance and reduces code size. Here’s how:
The story is very different for managed code where exceptions are very much an integral part of the runtime and thus cannot be avoided. Of course managed exceptions more than make up for the pitfalls with exception handling by providing a standard base class with exception information including the call stack at the time an exception was thrown thus greatly improving the ability for developers to track down bugs.