当ini文件不存在时,使用Boost属性树读取INI文件

时间:2014-09-10 08:31:34

标签: c++ visual-c++ boost

我正在使用Boost.PropertyTree加载INI文件:

read_ini( INI_FILE_NAME, pt );

如果ini文件不存在,则Boost会引发异常。

如何在不升级异常的情况下阅读ini文件,但获取不存在的信息?

2 个答案:

答案 0 :(得分:2)

你做不到。您必须处理所有异常并选择要使用/显示的内容。

try
{
     read_ini( INI_FILE_NAME, pt );
}
catch( std::exception &ex )
{
    // you either print it out or have a MessageBox pop up or hide it.
    std::cerr << ex.what( ) << std::endl;
}

相应地处理异常。

答案 1 :(得分:0)

按如下方式构建代码以正确处理异常

try
{
    read_ini(INI_FILE_NAME, pt);

    //Do something with pt
}
catch(ptree_bad_data& ex)
{
    // Log or error string stating that the data read is corrupt
}
catch(ptree_bad_path& ex)
{
    // Log or error string stating that there was problem in 
    // accessing the INI at the given location.
}
catch(ptree_error& ex)
{
    // Log or error string stating generic ptree exception.
}
catch(...)
{
    // Log or error string stating a generic exception.
    // Might want to rethrow the exception to address it correctly.

    //throw;
}

。 。

这将处理您的异常,避免尝试使用未填充的pt并告诉您过程中发生的确切问题,同时允许您的代码继续而不会中止。