Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 1000
iammilind Avatar asked Aug 08 '11 15:08

iammilind


People also ask

What happens if a constructor throws an exception?

When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.

Should a constructor throw an exception?

Yes, constructors are allowed to throw an exception in Java. A Constructor is a special type of a method that is used to initialize the object and it is used to create an object of a class using the new keyword, where an object is also known as an Instance of a class.

Are global objects allowed in C++?

It can be convenient to use C++ objects as global variables. You must be careful about what you do in the constructor, however. The first code example is the bad example, don't do this. Making MyClass myClass a global variable is fine, and is a useful technique.

Which of the following should not throw an exception?

I also know that the following cannot throw exceptions either: Destructors. Reading/writing primitive types.


2 Answers

If you NEED a global instance of an object whose constructor can throw, you could make the variable static, instead:

A * f(){

   try {

      //lock(mutex);   -> as Praetorian points out
      static A a;
      //unlock(mutex);

      return &a;
   }
   catch (...){

      return NULL;
   }
}

int main() {

   A * a = f(); //f() can be called whenever you need to access the global

}

This would alleviate the problem caused by a premature exception.

EDIT: Of course, in this case the solution is 90% of the way to being a Singleton. Why not just fully turn it into one, by moving f() into A?

like image 170
J T Avatar answered Sep 28 '22 06:09

J T


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.

like image 32
sharptooth Avatar answered Sep 28 '22 08:09

sharptooth