Unnamed Exception? From Whom?

May 11, 2007 21:55

At work today, I was dealing with an unnamed exception. I grepped our code to confirm that we didn't throw an exception without a good, descriptive string to go along with it. When I caught the exception and called its what() method, it would always return "Unnamed exception". WTF? Would a well-implemented library really throw without any information as to why? Fortunately, I checked the man page for exception(3C++) and discovered the awful truth. My try-catch block was
try { //stuff } catch (exception e) { // prints "Exception: Unnamed exception" cout << "Exception: " << e.what << endl; }
It compiled OK, which left me even more baffled. The answer turned out to be painfully simple. I had to catch a reference to an exception instead of an exception. I didn't have to change the e.what for a reference, but suddenly it was returning the correct text string.
try { //stuff } catch (const std::exception& e) { // prints the text associated with the exception cout << "Exception: " << e.what << endl; }
This is really perplexing to me. I need a language lawyer to explain why it would magically work when it was a reference but not when it was a copy. If it's going to break for bad punctuation, shouldn't it break at compile time?

programming, work

Previous post Next post
Up