user1000107
user1000107

Reputation: 415

Can a C++ program work well even though an exception is thrown from a class?

This is an interview question, the interview has been done.

Given a class A with members of Class B and C. If an exception happens in class C's constructor but the program can still work well, what is the reason ?

My answer:

The class C's constructor is not implemented by A. Or, A does not have some instructions to perform some operations on class C.

Class C does not have any instantiation.

Exception is not an error. Exception handler function handle it well.

Any better ideas ?

thanks !

Upvotes: 1

Views: 109

Answers (4)

Attila
Attila

Reputation: 28772

To successfully construct an object of A, you need to have successfully constructed its members (of type B and C in this case). If the program is wokring correctly, that means that it could recover from the failure of creating the A object.

The program must have caught the exception thrown from A's constructor and deal with the error situation in some way.

For example, you could pass a different set of parameters to A's constructor (which in turn pass different parameters to its C member ctor, which now does not throw), e.g. based on alternative configuration values.

Or there was an alternative path to solve the original problem that did not involve creating an object of type A (e.g. this alternative path might be more expensive to compute, which might have been the reason it was not the first choice).

Upvotes: 1

CB Bailey
CB Bailey

Reputation: 792657

The program can continue to work, if designed to do so, but the construction of the object of type A must fail as it's not possible for an object to be constructed completely if any of its bases or members fail to initialize.

It would be possible for a class to hold an object by an owning pointer and for it to be constructed without the held object provided that an expection doesn't escape from the initailizer list. E.g.

struct C {
    C();
};

struct A {
    A();
    std::unique_ptr<C> c;
};

A::A() {
    try {
        c.reset(new C);
    }
    catch (...){
        // oops. Can't re-throw, could log
    }
}

Upvotes: 0

sbabbi
sbabbi

Reputation: 11191

I think it is referring to this syntax:

 A::A() try : B(...),C(...) 
 {
    //A constructor body
 }
 catch(...) {}

EDIT nevermind, every exception not explicitly re-throw in the catch block is automatically rethrow

See this

Upvotes: 1

Hakan Serce
Hakan Serce

Reputation: 11256

If an instance of C is an optional member of class A, that is having a null valued pointer to a C instance is OK. Then, there would be no problem assuming proper exception handling.

Upvotes: 1

Related Questions