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

Reading INI file using Boost Property Tree when ini file not exist

本文关键字:INI 文件 属性 读取 Boost 不存在 使用      更新时间:2023-10-16

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

read_ini( INI_FILE_NAME, pt );

若ini文件不存在,则Boost引发异常。

如何在不出现异常的情况下读取ini文件,但却得到它不存在的信息?

你不能。您必须处理所有异常,并选择要使用的异常/显示异常。

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;
}

只需相应地处理异常即可。

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

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,并告诉您过程中发生的确切问题,同时允许您的代码继续而不中止。