Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variable outside try-catch block

Tags:

c++

c++11

I have the following code:

class ClassA
{
public:
    ClassA(std::string str);
    std::string GetSomething();
};

int main()
{
    std::string s = "";
    try
    {
        ClassA a = ClassA(s);
    }
    catch(...)
    {
        //Do something
        exit(1);
    }

    std::string result = a.GetSomething();

    //Some large amount of code using 'a' out there.
}

I would like the last line could access the a variable. How could I achieve that, given ClassA doesn't have default constructor ClassA() and I would not like to use pointers? Is the only way to add a default constructor to ClassA?

like image 908
Darxis Avatar asked Dec 15 '15 11:12

Darxis


1 Answers

You can't or shouldn't. Instead you could just use it within the try block, something like:

try
{
    ClassA a = ClassA(s);

    std::string result = a.GetSomething();
}
catch(...)
{
    //Do something
    exit(1);
}

The reason is that since a goes out of scope after the try block referring to the object after that is undefined behavior (if you have a pointer to where it were).

If you're concerned with a.GetSomething or the assignment throws you could put a try-catch around that:

try
{
    ClassA a = ClassA(s);

    try {
        std::string result = a.GetSomething();
    }
    catch(...) {
        // handle exceptions not from the constructor
    }
}
catch(...)
{
    //Do something only for exception from the constructor
    exit(1);
}
like image 144
skyking Avatar answered Sep 27 '22 00:09

skyking