Try / catch "in the middle" of a C ++ class constructor

Possible duplicate:
Difference between try-catch syntax for function

A few days ago I was reading a book about C ++ (this cloud was even a book by Bjarne Stroustrup), and I found this approach in the chapter on exceptions:

class Foo : public Bar { // ... }; // ... Foo::Foo try : Bar () { // ... } catch (const std::exception& error) { // ... } 

I don’t know why, but this design looks strange to me. However, it is very powerful because it gives me the ability to handle the exception thrown by the top-level constructor of the base class inside.

I have been using C ++ for several years, and I thought that I know this language pretty well ... What is wrong with this approach? Why is this often not mentioned in C ++ books?

+4
source share
3 answers

The real reason is that you can do very little in this catch block. You can do something like logging in or instead of another exception, but if you get to the end of the catch block without throwing metal, the original exception will be automatically returned.

Herb Sutter explains this very well in this article .

+3
source

Not so often, a class constructor can recover from an exception thrown by one of its dependencies. That is why you do not see this form more often. Plus, as you say, it looks weird.

0
source

You can catch an exception, but it will not help you because your objects were not created.

You cannot use an object, you cannot use its members. This violates RAII.

The only thing you can do is to rebuild the exception, maybe with additional information that clarifies the situation.

0
source

Source: https://habr.com/ru/post/1398880/


All Articles