What is the purpose of a function try block? [duplicate]
Asked Answered
T

2

9

Possible Duplicate:
When is a function try block useful?
Difference between try-catch syntax for function

This code throws an int exception while constructing the Dog object inside class UseResources. The int exception is caught by a normal try-catch block and the code outputs :

Cat()  
Dog()  
~Cat()  
Inside handler

#include <iostream>
using namespace std;

class Cat
{
    public:
    Cat() { cout << "Cat()" << endl; }
    ~Cat() { cout << "~Cat()" << endl; }
};

class Dog
{
    public:
    Dog() { cout << "Dog()" << endl; throw 1; }
    ~Dog() { cout << "~Dog()" << endl; }
};

class UseResources
{
    class Cat cat;
    class Dog dog;

    public:
    UseResources() : cat(), dog() { cout << "UseResources()" << endl; }
    ~UseResources() { cout << "~UseResources()" << endl; }
};

int main()
{
    try
    {
        UseResources ur;
    }
    catch( int )
    {
        cout << "Inside handler" << endl;
    }
}

Now, if we replace the definition of the UseResources() constructor, with one that uses a function try block, as below,

UseResources() try : cat(), dog() { cout << "UseResources()" << endl; } catch(int) {}

the output is the same

Cat()  
Dog()  
~Cat()  
Inside handler 

i.e., with exactly the same final result.

What is then, the purpose of a function try block ?

Toothpick answered 2/12, 2011 at 16:43 Comment(6)
Duplicate of a duplicate of a duplicate of a...Crownwork
Is this c++11? I never saw it beforeForemast
@VJovic I don't know when this was introduced in the language. But it is not new.Toothpick
@VJovic it's C++03. Pretty much unused.Fulcrum
This is what you were looking for, @Xeo. Possible duplicate of When is a function try block useful? See also Difference between try-catch syntax for function.Ellaelladine
@Rob: Thanks for searching, I was on my iPhone at the time of posting my comment, and searching for something and then closing a question is a hassle on it. :)Crownwork
I
13

Imagine if UseResources was defined like this:

class UseResources
{
    class Cat *cat;
    class Dog dog;

    public:
    UseResources() : cat(new Cat), dog() { cout << "UseResources()" << endl; }
    ~UseResources() { delete cat; cat = NULL; cout << "~UseResources()" << endl; }
};

If Dog::Dog() throws, then cat will leak memory. Becase UseResources's constructor never completed, the object was never fully constructed. And therefore it does not have its destructor called.

To prevent this leak, you must use a function-level try/catch block:

UseResources() try : cat(new Cat), dog() { cout << "UseResources()" << endl; } catch(...)
{
  delete cat;
  throw;
}

To answer your question more fully, the purpose of a function-level try/catch block in constructors is specifically to do this kind of cleanup. Function-level try/catch blocks cannot swallow exceptions (regular ones can). If they catch something, they will throw it again when they reach the end of the catch block, unless you rethrow it explicitly with throw. You can transform one type of exception into another, but you can't just swallow it and keep going like it didn't happen.

This is another reason why values and smart pointers should be used instead of naked pointers, even as class members. Because, as in your case, if you just have member values instead of pointers, you don't have to do this. It's the use of a naked pointer (or other form of resource not managed in a RAII object) that forces this kind of thing.

Note that this is pretty much the only legitimate use of function try/catch blocks.


More reasons not to use function try blocks. The above code is subtly broken. Consider this:

class Cat
{
  public:
  Cat() {throw "oops";}
};

So, what happens in UseResources's constructor? Well, the expression new Cat will throw, obviously. But that means that cat never got initialized. Which means that delete cat will yield undefined behavior.

You might try to correct this by using a complex lambda instead of just new Cat:

UseResources() try
  : cat([]() -> Cat* try{ return new Cat;}catch(...) {return nullptr;} }())
  , dog()
{ cout << "UseResources()" << endl; }
catch(...)
{
  delete cat;
  throw;
}

That theoretically fixes the problem, but it breaks an assumed invariant of UseResources. Namely, that UseResources::cat will at all times be a valid pointer. If that is indeed an invariant of UseResources, then this code will fail because it permits the construction of UseResources in spite of the exception.

Basically, there is no way to make this code safe unless new Cat is noexcept (either explicitly or implicitly).

By contrast, this always works:

class UseResources
{
    unique_ptr<Cat> cat;
    Dog dog;

    public:
    UseResources() : cat(new Cat), dog() { cout << "UseResources()" << endl; }
    ~UseResources() { cout << "~UseResources()" << endl; }
};

In short, look on a function-level try-block as a serious code smell.

Interconnect answered 2/12, 2011 at 16:50 Comment(14)
Interesting. None of the examples I've seen so far with function try blocks this cleanup thing showed up. But in your example the program will abort anyway, so what's the big deal with this feature ? What's the purpose of the cleanup if the OS is going to that anyway ?Toothpick
Exception handling is not about working through failure it's about handling failure more gracefully. This feature helps you gracefully release resources. A practical example might be a client crashing and using this to free server resources so that it doesn't leave it inoperable for other clients.Confabulate
@Confabulate But terminate() will always be called with a function try block, and in this case any resource is going to be freed by the OS. Isn't that true ?Toothpick
Where do you get the idea that terminate will be called, @User? There's nothing special about function try blocks in that regard. It's going to catch an exception thrown during member initialization, and then rethrow it. That's perfectly normal exception behavior. Whoever called the constructor will have the opportunity to catch it next. An exception-throwing constructor is not grounds for automatic program termination.Ellaelladine
@user1042389: Releasing resources is different from freeing memory. The application may terminate after an exception and the OS may free memory allocations but that won't necessarily correct state of other processes.Confabulate
@Rob Kennedy Some exception will always be thrown from the catch{} clause in a function try block by definition. As far as I can understand, at some point terminate() will be invoked, otherwise you would have an object not entirely constructed, if that term is correct.Toothpick
@user1042389: No. A constructor that emits an exception means that the object was never constructed. An exception will float up the call stack until it hits the of main. If it doesn't find any viable catch statements, it will terminate the program. But if it does find viable catch blocks, then that's where it will transfer control. The catch block cannot access the object that was never created, since it was never created.Interconnect
@NicolBolas I understand that when a constructor emits an exception the object is not constructed. Assuming, as you said, there is a catch block, for example in main() that catches the exception emitted in the constructor, that exception, or another, will be rethrown, an then terminate() will be invoked.Toothpick
@user1042389: No, it will not. catch only automatically rethrows an exception if it's a function-level catch. A catch within a function can choose to or not to rethrow the exception. If it doesn't, execution continues after the catch block ends.Interconnect
@user1042389: The OS will reclaim memory, but it won't disconnect you from the database, issue the appropriate RPC calls, or any of the numerous other things your resource management might require.Convene
@Nicol Your're right. Only the catch block at the function try block requires an exception to be thrown. I thought the same would apply to all others catch clauses, which is not correct. I'm giving you the credit for the answer. Thanks.Toothpick
@NicolBolas I believe your code is not safe: If new Cat throws an exception, then the catch block will be executed too. There you call delete on a pointer that then contains garbage. This pointer could contain a valid memory address which would lead to a bad program crash.Tenia
@RalphTandetzky: You're right. And there's pretty much no way to resolve that. Even if you use a complex lambda to try to initialize cat, one which catches the new Cat exception, you're still boned. Because that lambda cannot initialize cat to nullptr if it catches. Not unless it absorbs the exception, which would violate the outer class's precondition of having a valid cat instance.Interconnect
"The behavior is undefined if the catch-clause of a function-try-block used on a constructor or a destructor accesses a base or a non-static member of the object." from en.cppreference.com/w/cpp/language/function-try-blockIgnacia
O
2

Ordinary function try blocks have relatively little purpose. They're almost identical to a try block inside the body:

int f1() try {
  // body
} catch (Exc const & e) {
  return -1;
}

int f2() {
  try {
    // body
  } catch (Exc const & e) {
    return -1;
  }
}

The only difference is that the function-try-block lives in the slightly larger function-scope, while the second construction lives in the function-body-scope -- the former scope only sees the function arguments, the latter also local variables (but this doesn't affect the two versions of try blocks).

The only interesting application comes in a constructor-try-block:

Foo() try : a(1,2), b(), c(true) { /* ... */ } catch(...) { }

This is the only way that exceptions from one of the initializers can be caught. You cannot handle the exception, since the entire object construction must still fail (hence you must exit the catch block with an exception, whether you want or not). However, it is the only way to handle exceptions from the initializer list specifically.

Is this useful? Probably not. There's essentially no difference between a constructor try block and the following, more typical "initialize-to-null-and-assign" pattern, which is itself terrible:

Foo() : p1(NULL), p2(NULL), p3(NULL) {
  p1 = new Bar;
  try {
    p2 = new Zip;
    try {
      p3 = new Gulp;
    } catch (...) {
      delete p2;
      throw;
    }
  } catch(...) {
    delete p1;
    throw;
  }
}

As you can see, you have an unmaintainable, unscalable mess. A constructor-try-block would be even worse because you couldn't even tell how many of the pointers have already been assigned. So really it is only useful if you have precisely two leakable allocations. Update: Thanks to reading this question I was alerted to the fact that actually you cannot use the catch block to clean up resources at all, since referring to member objects is undefined behaviour. So [end update]

In short: It is useless.

Ourself answered 2/12, 2011 at 17:11 Comment(1)
"It is useless." Unless of course you want to translate exceptions.Interconnect

© 2022 - 2024 — McMap. All rights reserved.