How to access objects that have been initialized in a try statement

I am new to C ++ and was wondering if you can do the following, or if you have a better way.

I have a custom exception class for my database handler: I use it basically like this:

int main(int argc, char const ** argv){
    try {
        DatabaseHandler DGeneDB = DatabaseHandler("string/to/path");
    }catch(DatabaseHandlerExceptions &msg) {
        std::cerr << "Couldn't open Database" << std::endl;
        std::cerr << msg.what();
        return 1;
    }
    DGeneDB.foo() //Can't access this object since it was initialized in try statement
    return 0;
}

      

I have a billion things I want to do with a DGeneDB object and I don't want to do all of this in a try statement. I only want to catch a constructor exception that is thrown during initialization. What should I do to work with an object outside of a try? I mean, if it throws an exception, it will return 1 and stop main () before it gets another object.

+3


source to share


1 answer


Does yours have a Databasehandler

method open

or something similar? If not, create it and change that constructor so that it doesn't open the database connection anymore (so it won't throw). Your code will look like this:

DatabaseHandler DGenDB;
try {
    DGenDB.open(dbpaths.Dgene_db);
}
catch (DatabaseHandlerExceptions &msg) {
    return 1;
}

      

Note: In your source code, you have a line like this:



DatabaseHandler DGeneDB = DatabaseHandler(dbpaths.Dgene_db);

      

This is an unusual way to initialize variables in C ++. You could just write:

DatabaseHandler DGeneDB(dbpaths.Dgene_db);

      

+2


source







All Articles