The returning function that never returned

Investigating a crash report yesterday, I came across this piece of code (simplified for the purpose of this post):

std::string foo() try {
    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 Response to “The returning function that never returned”

  1. What’s the Point of Function Try Blocks « C++ on a Friday Says:

    […] } This post is a follow up to The Returning Function that Never Returned, which I wrote a couple of months ago. You can read it first if you want, it is only around a […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: