dev
dev

Reputation: 2200

How to declare a variable in Try and access it in Catch?

I am creating an object of my class in try/catch block and want to access it in catch block in case of exception. Even if the object is created ok, I cannot access it in catch block as it declared outside the block.

 try {
    MyObject ob(arg1,arg2); //this can trow exception

    ob.func1(); //this also can throw exception

} catch (std::exception& ex){
    //I want to access ob here if it was constructed properly and get the reason why func1() failed
}

I can use nested try/catch blocks to solve this issue but is there any other way to solve this

try {
    MyObject ob(arg1,arg2); //this can trow exception
    try {

        ob.func1(); //this also can throw exception
    } catch(std::exception& ex) {
        //object was constructed ok, so I can access reason/state why the operation failed
    }
} catch (std::exception& ex){
    //object failed to construct
}

Upvotes: 2

Views: 4653

Answers (3)

Christopher J.
Christopher J.

Reputation: 1283

No, you cannot access an object out of scope. But to answer this:

get the reason why func1() failed

If the object construction failed because of an exception, this means that the std::exception already contains some information about why it has failed. So you have to do this in your code:

catch (std::exception& ex){
    // object failed to construct
    std::cout << ex.what() << std::endl;
}

Upvotes: 1

Quentin
Quentin

Reputation: 63144

Andrei Alexandrescu's ScopeGuard might help here:

try {
    MyObject ob(arg1,arg2);

    SCOPE_FAIL { /* Handler 1 */ };

    ob.func1();

} catch (std::exception& ex) {
    /* Handler 2 */
}

The body of SCOPE_FAIL will be executed if its scope is left via stack unwinding, that is, an exception has been thrown. Unfortunately you can't access the exception itself there, but you can access ob.

The rest of the program behaves as usual, so the execution looks like:

  1. ob is successfully constructed;
  2. ob.func1() is executed and throws;
  3. /* Handler 1 */ is executed;
  4. ob is destructed;
  5. /* Handler 2 */ is executed.

Upvotes: 0

SergeyA
SergeyA

Reputation: 62603

No, you can not do this. It is not possible to access this variable from same-level catch block.

The solution is to stop using exceptions as a flow control mechanism - they are not - and use them as they are, an indication of exceptional situation - in which case it doesn't really matter what did throw.

Upvotes: 4

Related Questions