【问题标题】:Reading INI file using Boost Property Tree when ini file not exist当ini文件不存在时使用Boost Property Tree读取INI文件
【发布时间】:2014-09-10 08:31:33
【问题描述】:

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

read_ini( INI_FILE_NAME, pt );

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

如何读取ini 文件而不出现异常,但获取它不存在的信息?

【问题讨论】:

  • 您是否考虑过捕获异常?
  • 希望boost有更优雅的解决方案
  • Exception 在您有文件但打开错误文件的情况下也很有用。即您打开的是 jpg 图像,或者文件格式存在一些错误,例如缺少结束标签。这些,就像丢失的文件一样,不允许读取信息,因此抛出相同结果的异常(无信息)。
  • 如果你调用异常不优雅,你可以考虑使用不同的语言。异常是 C++ 的核心机制,是的,它很优雅。

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


【解决方案1】:

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

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

只需相应地处理异常。

【讨论】:

  • 这会在解析失败时抛出异常,不仅是在文件不存在时,而且它没有解决“如何读取ini文件而不出现异常”的问题
  • @PiotrS。这会捕获所有异常,您对异常的处理取决于您,因此它回答了问题。它总是会引发异常,或者至少是应该引发的 boost 错误代码。
  • 准确地说,这会捕获从std::exception 派生的所有异常。如果他询问如何在没有例外的情况下解决问题,请不要假设 OP 可以使用例外
【解决方案2】:

如下构造您的代码以正确处理异常

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 2013-04-18
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多