Search code examples
c++boostboost-propertytree

How to not have any error when try to get a not existing node


Could somebody knows what kind of exception return the following code inside the "try" ? I try to use the 3 kind of "catch (exception)" and no one seems to work.

try
{
    std::cout << "try to get not existing path" << std::endl;
    std::string path = this->m_Tree.get<std::string>(PATH);
}
catch (const boost::property_tree::ptree_bad_path& e)
{
    std::cout << "ptree_bad_path" << std::endl;
}

Thank you for your help.


Solution

  • Look at the docs:

    Three Ways of Getting Data

    There are three versions of get: get, get (default-value version), and get_optional, which differ by failure handling strategy. All versions take path specifier, which determines in which key to search for a value. It can be a single key, or a path to key, where path elements are separated with a special character (a '.' if not specified differently). For example debug.logging.errorlevel might be a valid path with dot as a separator.

    So, just use get_optional<std::string> I'd say

    ptree pt;
    /* ... */
    boost::optional<float> v = pt.get_optional<float>("a.path.to.float.value");