Suppose I want client code to override exception behaviour. What is the most appropriate way of doing this? It is understood that the callback must not return to its caller: It should either abort, or throw an exception in the format catched by the client catch clause.

  1. A global singleton which is initialized during library startup
  2. An exception policy which is passed to each function that can throw an exception
  3. Skip this customization point

The first choice is likely to be easier after the library has been initialized, but suffers from initialization requirements, and threading issues.

try
    {
    MyExceptionPolicy ep;
    MyLib::init(ep);
    MyLibb::Foo bar; //Ctor will call method in ep
    //use bar
    }
catch(const MyExceptionType& obj)
    {
    cerr<<obj.message();
    return -1;
    }
return 0;

The second choice is more flexible, but results in an ugly API. I guess this is why we have the global standard streams, so one does not need to pass references to these objects everywhere.

try
    {
    MyExceptionPolicy ep;
    MyLib::Foo bar(ep); //Ctor will call method in ep. Can be implemented as a template, resulting in compile-time dispatch, rather than runtime dispatch.
    //use bar
    }
catch(const MyExceptionType& obj)
    {
    cerr<<obj.message();
    return -1;
    }

As an alternative approach, it is possible to use multiple catch clauses. This does not require an ExceptionPolicy but, requires one catch clause per involved library, again making client code look ugly (if-else style exceptions).

try
    {
    MyLib::Foo bar;
    //use bar
    }
catch(const MyLib::ExceptionType& obj)
    {
    cerr<<obj.messageMyLibWay();
    return -1;
    }
catch(const MyExceptionType& obj)
    {
    cerr<<obj.message();
    return -1;
    }
share|improve this question

closed as off-topic by Loki Astari, forsvarir, Edward, t3chb0t, denis Jan 14 at 16:00

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

    
That will be highly dependant on situation. There is no best way. For examples in the standard library see: cplusplus.com/reference/ios/ios/exceptions Voting to close as the question is asking for an opinion not a review. – Loki Astari Jan 14 at 14:32
    
@LokiAstari which is option number 2, with mutable state. Is the question more appropriate for software engineering? – user877329 Jan 14 at 14:42
    
Probably the best. – Loki Astari Jan 14 at 14:50