Exceptions vs status returns

Tuesday 16 September 2003This is 21 years old. Be careful.

I had thought that this debate was long over, but the other day I found myself arguing the benefits of throwing exceptions vs. returning status codes. Since I had to go through the whole thing, I’ve written them up. Maybe this will help put the argument to rest: Exceptions vs. status returns

Comments

[gravatar]
Good writeup. I think this is more of an issue with the C/C++ camp than with more recent languages.

When you settle on the exception approach, the next debate is checked vs. unchecked exception. Java and C# made different choices in this case. There were a couple of recent discussions on this.
Follow my links: http://www.bobcongdon.com/blog/2003_08_01_congdon_archive.html
[gravatar]
Don't forget the old chestnut about how try/catch blocks are slow because of the code overhead (cue for Bob to blog that Sun JVM vs MS JVM for exception handling versus array.length() thingy).

And don't forget the problem when you throw an exception in a d'tor whilst unwinding the stack due to another exception. Bjarne's advice: "don't do that"
[gravatar]
I can't find a citation for the Microsoft vs. Sun JVM. The story was that you could iterate through an array faster in the Microsoft JVM by catching ArrayIndexOutOfBounds rather than doing a bounds check on every iteration. Sun's JVM performance was degraded with the same code. Unless you're doing array processing and trying squeeze out every last cycle, this hack is likely to be worthless. And if you do care at that level you should drop down and use native code and JNI instead.

Regarding throwing exceptions from destructors. Yeah, don't do that. It's really bad. Throwing exceptions from constructors in C++ can be very tough to handle too.

Also, exceptions should mostly be used for errors, exceptional cases. I've worked on projects where exceptions happen during normal processing. The code flow can get very, very messy. Also, multiply nested try/catch blocks in a single method ain't a lot of fun.
[gravatar]
A bit of C++ exception trivia. According to Strotrup, C++ exceptions were inspired by the ML programming language. But ML used "raise" rather thna "throw". So why did Stroustup use "throw"? Answer in the next comment...
[gravatar]
He couldn't use raise because it was part of the standard C library. (That's what happens when you have a flat namespace and other developers grab all of the "good" words). So he picked "throw" instread. By the way, throw/catch were the names used by Lisp and Stroustrup felt they were better than any other alternatives they came up with.

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.