Shit You Don't Do In C++ (Post #1)
Dec. 11th, 2008 10:35 amAs part of refocusing on my career and getting back to a place I enjoy and want to work I’m going to start posting more about programming, debugging and working on Windows. My plan is to focus on a particular skill I have which is to diagnose and repair crashes and hard to find bugs. There is probably going to be some good generic information for any language and operating system but Microsoft Windows and C++ is where I make my living so that’s where I’m going to focus.
Before I getting into the meat of today’s post I’m going to say that these are all real problems I’ve found in my career. Not all of them are from my current employer. I have mangled any samples to keep the problem handy but not reveal any privileged information. So let me start with a post that belongs in my book Shit You Don’t Do In C++.
The exception handling system in C++ is an often misused and misunderstood feature. Used properly it can make programs more robust and much easier to maintain. Used improperly, as in today’s case, exception handling makes finding a bug take a lot longer than necessary. For example, it took me hours to track down a bug because the exception handler hid the true problem and the program crashed in a different area. Here is an example of what not to do:
( C++ Snippet )Hopefully any developers reading this are cringing as much as I did
when I found it. On line 19 we are casting a Shape
into a Circle
.
This is bad cast as Circle
is derived from Shape
. The
dynamic_cast
operator in C++ specifies that an invalid cast throws
a std::bad_cast
exception. This is expected and the correct
behavior. The fault comes from the catch
block on lines 21 and
22. The code catches the exception and does nothing with it. So the
program continued on it’s merry way until another section tried to use
ref_circle
.
Never, and I really mean never, use a catch
handler to hide an
exception. If you don’t take care of the exception right there and
then just let it travel up the chain to someone who will handle it.
That someone might be the OS who will report the where the exception
originated so you can find the problem and fix it. I’ve seen people
argue that the program should never crash and this is one way to
prevent it. If your program really should never crash, and the one I
work on is one of those, then you’re better off to let it crash while
developing and testing and fix the real problems instead of just
hiding your head in the sand.