2011-07-27 15 views
5

私は最近boost :: exceptionの使用を開始しました。今私は、boost :: errinfo_nested_exceptionを使ってエラーの原因に関する情報を出力したいと思います。問題は、原因から情報を取得する方法を理解できないことです。ノー成功を収めて、次の試してみました:boost :: errinfo_nested_exceptionから情報を抽出するにはどうすればよいですか?

#include <iostream> 
#include <boost/exception/all.hpp> 

struct myex : public virtual boost::exception {}; 

int main() 
{ 
    myex cause; 
    cause << boost::errinfo_file_name("causefile.cpp"); 

    try { 
     myex ex; 
     ex << boost::errinfo_nested_exception(boost::copy_exception(cause)); 
     throw ex; 
    } 
    catch (myex& e) { 
     // Here I would like to extract file name from cause and print 
     // it in a nice way, but I cant figure out what to do with a 
     // boost::exception_ptr. 
     const boost::exception_ptr* c = 
     boost::get_error_info<boost::errinfo_nested_exception>(e); 

     // I cant do this: 
     // const std::string* file = boost::get_error_info<boost::errinfo_file_name>(*c); 

     // Nor this: 
     // const std::string* file = boost::get_error_info<boost::errinfo_file_name>(**c); 

     // This works fine and the nested exception is there, but that's not what I want. 
     std::cout << boost::diagnostic_information(e) << std::endl; 
    } 

    return 0; 
} 

答えて

2

あなたは、ネストされた例外を再スローし、それを検討する必要があります。

const boost::exception_ptr* c = 
    boost::get_error_info<boost::errinfo_nested_exception>(e); 
if(c) try { 
    boost::rethrow_exception(*c); 
} catch(boost::exception const& e) { // or a type derived from it 
    const std::string* file = boost::get_error_info<boost::errinfo_file_name>(e); 
    // ... 
} catch(...) { 
    // presumably you don't want the exception to escape if it is 
    // not derived from boost::exception 
} 

私は個人的に結果を返すget_error_infoラッパーを使用boost::get_error_info<some_error_info>(e)のいずれかが見つからない場合、またはネストされた例外がない場合(error_infoが有効でない場合)(ここでの再帰呼び出し)または0の結果が見つからない場合

代わりに/補完するものとして、あなたが関数内で(異なるcatch節)上記のチェックコードを考慮することができます

std::string const* // or return a tuple of what you examined etc. 
examine_exception() 
{ 
    try { 
     throw; // precondition: an exception is active 
    } catch(boost::exception const& e) { 
     // as above 
     return ...; 
    } 
} 
+0

ビットそれをretrhowする必要があるために、奇妙な、しかし私は、ブーストで奇妙だと思います。多分それはタイピングと関係があります。とにかく、それは私の問題を解決しました。 ;) – ygram

+0

@ygramこれは 'boost :: exception_ptr'がどのように指定されているかということから来ています。そのインタフェースは非常に最小限であり、(ポインタ自体ではなく)* stored *例外に役立つ何かを行う唯一の方法は、 。それが 'std :: exception_ptr'に受け入れられたことと、言語が例えば' 'int'は、実際にはかなり固いデザインです。 –

関連する問題