2014-09-10 101 views
2

我使用Boost.PropertyTree加載INI文件:讀INI文件時INI文件不存在

read_ini(INI_FILE_NAME, pt); 

如果ini文件存在,那麼Boost產生異常。

如何閱讀ini文件沒有上升的異常,但獲取信息,它不存在?

+4

您是否考慮捕捉異常? – WhozCraig 2014-09-10 08:33:50

+0

我希望boost能有更優雅的解決方案 – vico 2014-09-10 08:38:52

+0

如果你有文件但是打開了錯誤的文件,異常也很有用。即您打開一個jpg圖像,或文件格式有一些錯誤,如缺少結束標籤。這些,就像丟失的文件一樣,不允許讀取信息,所以拋出相同結果的異常(沒有信息)。 – Jepessen 2014-09-10 08:53:02

回答

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

只處理相應的異常。

+0

這會拋出異常,如果解析失敗,不僅文件不存在時,而且它不解決問題*「如何讀取ini文件沒有上升的異常」* – 2014-09-10 08:41:30

+0

@PiotrS。這會捕獲所有異常情況,而您所做的異常由您決定,因此它可以回答問題。它總是會引發一個異常,或者至少會引發一個錯誤代碼。 – deW1 2014-09-10 08:43:43

+0

這會捕獲從'std :: exception'派生的所有異常。並且如果他詢問如何無例外地解決問題,不要假設OP可以使用例外 – 2014-09-10 08:46:26

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並告訴您發生在流程中的確切問題,同時允許您的代碼在不中止的情況下繼續。