4

Possible Duplicate:
Difference between try-catch syntax for function

Few days ago I was reading a book about C++ (it cloud be even a Bjarne Stroustrup's book) and I found such approach in chapter about exceptions:

class Foo :
    public Bar
{
   // ...
};

// ...

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

I don't know why but this construction looks weird for me. However it's very powerful, because it gives me ability to handle exception thrown by base class "inside" toplevel constructor.

I'm using C++ for few years and I thought, that I know this language pretty good... What's wrong with this approach? Why it's not mentioned often event in C++ books?

Community
  • 1
  • 1
Goofy
  • 5,187
  • 5
  • 40
  • 56
  • 4
    so you catch the exception.. then *what* ? how would you handle it? – Karoly Horvath Feb 28 '12 at 19:01
  • @larsmans: Normally, exceptions are not re-thrown automatically. Which is the case with constructor-level catch block. :-/ –  Feb 28 '12 at 19:11

3 Answers3

4

The real reason is that there is very little you can do in that catch block. You can do something like loging, or throwing a different exception instead, but if you reach the end of the catch block without throwing, the original exception wll be automatically rethrown.

Herb Sutter explains all this very well in this article.

Kevin Cathcart
  • 9,838
  • 2
  • 36
  • 32
  • 2
    +1 for gotw link. I think it's worth noting to the Goofy that this practice becomes mostly unnecessary when we adhere more strictly to RAII (smart pointer members, e.g., not raw pointers, file objects that close automatically like fstream, not fopen/fclose, etc). – stinky472 Feb 28 '12 at 19:13
0

It isn't very often that a class constructor can recover from an exception thrown by one of its dependencies. That's why you don't see this form more often. Plus, as you say, it looks kinda weird.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

You can catch exception, but it doesn't help you much, because your objects hadn't been constructed.

You can't use object, you can't use its members. It violates RAII.

The only thing you can do is to rethrow the exception, may be with some additional information that clarify situation.

Lol4t0
  • 12,444
  • 4
  • 29
  • 65