Search code examples
c++exceptionshared-ptrstack-unwinding

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 )
 {
 }

Solution

  • 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.