Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch exceptions thrown from constructor of a global instance of a class?

I know that having global variables is not appreciated. But in the book, The C++ programming language, by Bjarne Stroustrup, Author says that " The only way to gain control in case of throw from an initializer of a non local static object is set_unexpected() ". How is it done?

like image 966
sajas Avatar asked Dec 04 '12 04:12

sajas


People also ask

What happens if exception is thrown in constructor?

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.

How do you catch thrown exceptions in C++?

Exception handling in C++ is done using three keywords: try , catch and throw . To catch exceptions, a portion of code is placed under exception inspection. This is done by enclosing this portion of code in a try block. When an exception occurs within the try block, control is transferred to the exception handler.


1 Answers

I posted the question in some other forums and got some answers.

First one was to declare a pointer rather than having an object and to initialize it in main()

Second one was to derive the class (whose constructor throws the exception ) from another class which performs set_terminate so as to set a meaningful handler. The second one seems to work fine in codeblocks ide.

The code I used to test check it is:

void f()        //Unexpected exception handler
{
    cout<<"Terminate called "<<endl;
    exit (0);
}
class A         //Base class that performs set_unexpected
{
    terminate_handler h;
public:
    A()
    {
        h=set_terminate(f);
    }
    ~A()
    {
        set_terminate(h);
    }
};
class B:public A    //Derived class that throws unexpected_exception
{
public:
    B()
    {
        throw 1;
    }
};
B b;
int main()
{
}

The program displays the message: "Terminate called" and exits.

like image 182
sajas Avatar answered Sep 28 '22 07:09

sajas