0

I would like to ensure that, **whenever a class that throws an exception is constructed, there is a try-catch block to capture the exception right there **. In the example, I would like to get a warning from compiler when I create A object in the statement auto a = A(3); suggesting to add a try-catch block right there.

There is always freedom in C++ to decide where to capture exceptions. Is there any mechanism to ensure that the exception is caught at construction time? My final purpose is to ensure that by mistake, the exception of A is not caught somewhere else.

#include <stdexcept>

struct A
{
    A(int v) noexcept(false)
    {
      if (v < 10)
        throw std::invalid_argument( "Value is too small" );
      value = v;
    }

private:
    int value;
};

int main()
{
  auto a = A(3);
}
Pax
  • 134
  • 5
  • Not really, c++ doesn't offer this feature – Alan Birtles Nov 07 '22 at 11:02
  • *"My final purpose is to ensure that by mistake, the exception of A is not caught somewhere else"* - Why assume that will be a mistake? If that exception can only be handled up the call stack, why force a "try-catch-rethrow" dance on users of the class? – StoryTeller - Unslander Monica Nov 07 '22 at 11:03
  • For debug builds you could add an assert(v>=10). And for release (and debug) throw a specific exception (not a generic one like std::invalid_argument) indicating this constructor failed. Then add a catch for that exception in main and report since your program is in an unexpected state and should not continue. – Pepijn Kramer Nov 07 '22 at 11:13

0 Answers0