lurscher
lurscher

Reputation: 26983

throwing a boost::shared_ptr< customException>

is there any pitfall of the following;

 if (someCondition)
   throw boost::shared_ptr<SomeException>( new SomeException( "foo!" ) );

 ...

 catch( const boost::shared_ptr<SomeException>& expRef )
 {
 }

Upvotes: 1

Views: 674

Answers (3)

Edward Strange
Edward Strange

Reputation: 40877

Yes, there is a pitfall. You won't be able to catch based on base classes:

void f()
{
  throw std::runtime_error("look here");
}
void g()
{
  throw boost::shared_ptr<std::runtime_error>("look here");
}

int main()
{
  try
  {
    f();
  }
  catch ( std::exception const& e) {}

  try { g(); }
  catch ( boost::shared_ptr<std::exception> const& e) {} // no work
}

You could of course make it throw on base, but then you can't catch the derived.

So yeah...don't do it.

Upvotes: 4

Bo Persson
Bo Persson

Reputation: 92321

The only pitfall I can see is that you are doing something the hard way, when you don't have to. :-)

Normally you use a shared_pointer to manage the lifetime of an object, when that is not obvious otherwise. Here it is clear that it is not your responsibility to manage the exceptions thrown. The compiler will have to do that for you!

When the exception is handled, the runtime will destroy the shared_pointer that will then destroy the exception object. Otherwise the runtime would have destroyed the exception object directly! What do you gain?

Upvotes: 1

You should avoid throwing by pointer, and prefer throwing by value and catching by (const) reference.

Using a smart pointer is a way of simplifying resource management when using pointers, but if you can avoid using pointers altogether, it will be simpler doing so. Just throw a value.

Upvotes: 6

Related Questions