Elan Hickler
Elan Hickler

Reputation: 1139

How do you construct an object that can throw exception?

This is going to go out of scope so I can't use it.

try
{
    SomeClass someObject({});
}
catch (std::exception & e)
{

}

someObject(x); // someObject does not exist because it goes out of scope

Upvotes: 1

Views: 48

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596256

Construct the object dynamically, eg:

SomeClass *someObject = nullptr;

try
{
    someObject = new SomeClass(...);
}
catch (const std::exception &e)
{

}

// or:
// SomeClass *someObject = new(nothrow) SomeClass(...);

if (someObject)
{
    // use someObject as needed...
    delete someObject;
}

Alternatively:

std::unique_ptr<SomeClass> someObject;

try
{
    someObject.reset(new SomeClass(...));
    // or:
    // someObject = std::make_unique<SomeClass>(...);
}
catch (const std::exception &e)
{

}

if (someObject)
{
    // use someObject as needed...
}

Upvotes: 1

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

Here's a useful application of std::optional.

std::optional<SomeClass> maybe_someobject;

try {
     maybe_someobject.emplace( /* Constructor parameters go here */);
} catch (...  /* or something specific */)
{
     /* catch exceptions */
     return; // Do not pass "Go". Do not collect $200.
}

SomeClass &someobject=maybe_someobject.value();

// Use someobject normally, at this point. Existing code will have to look
// very hard to be able to tell the difference.

This adds a little bit overhead, but it's quite minimal, but you preserve complete type and RAII-safety.

Upvotes: 2

Related Questions