Investigating a crash report yesterday, I came across this piece of code (simplified for the purpose of this post):
std::string foo() try { bar(); return "foo"; } catch (...) { log("Unable to foo!") } int main() { std::string s = foo(); }
Today’s exercise: what happens if bar()
throws? Obviously, the function doesn’t return, since the exception is thrown and control is passed to the catch
block. But since this block does not return, and does not rethrow, foo() neither returns nor throws, so what goes into the string s
? Answer: No one knows, we are left in the happy land called undefined behaviour.
The morale? If the original implementor had used -Wall, he would have gotten a warning that execution reaches the end of the non-void function. (Both Sun Studio and gcc happlily compiles without complaining otherwise.)
Update:I have posted a follow up going into more details on function try blocks.
If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter
One thought on “The returning function that never returned”