Search code examples
c++exceptionglobal-variablescoding-style

If a constructor throws exception, then does it make sense to have a global object of that class?


I am asking this question for general coding guidelines:

class A {
  A() { ... throw 0; }
};
A obj;  // <---global

int main()
{
}

If obj throws exception in above code then, it will eventually terminate the code before main() gets called. So my question is, what guideline I should take for such scenario ? Is it ok to declare global objects for such classes or not ? Should I always refrain myself from doing so, or is it a good tendency to catch the error in the beginning itself ?


Solution

  • No, you should not declare such objects global - any exception will be unhandled and very hard to diagnose. The program will just crash which means that it will have very poor (below zero) user experience and will be rather hard to maintain.