6

私はC++ 11を使用していますが、からのエラーを処理しているため、この質問はブースト関連ですboost::file_system

次の状況では:

try {

     // If p2 doesn't exists, canonical throws an exception
     // of No_such_file_or_directory
     path p = canonical(p2);

     // Other code

} catch (filesystem_error& e) {

    if (e is the no_such_file_or_directory exception)
        custom_message(e);

} // other catchs
}

目的の例外 (no_such_file_or_directory) がスローされたときにエラー値を出力すると、次のようになります。

// ...
} catch (filesystem_error& e) {
     cout << "Value: " << e.code().value() << endl;
}

値を取得します2。と同じ値ですe.code().default_error_condition().value()

私の質問は、さまざまなエラー カテゴリのさまざまなエラー条件が同じ値を持つ可能性があるかどうかです。つまり、特定のエラーが発生していることを確認するために、エラー カテゴリとエラー値の両方を確認する必要がありますか? そのような場合、それを行う最もクリーンな方法は何ですか?

4

1 に答える 1

9

error_codesおよびerror_conditionswith differenterror_categoriesは、同じ を持つことができvalue()ます。非メンバー比較関数 は、値とカテゴリの両方をチェックします。

bool operator==( const error_code & lhs, const error_code & rhs ) noexcept;

戻り値: lhs.category() == rhs.category() && lhs.value() == rhs.value() .

したがって、次のように、からの戻り値に対して例外error_codeをチェックできます。make_error_code()

try {
  // If p2 doesn't exists, canonical throws an exception
  // of No_such_file_or_directory
  path p = canonical(p2);

  // ...    
} catch (filesystem_error& e) {
  if (e.code() ==
      make_error_code(boost::system::errc::no_such_file_or_directory)) {
    custom_message(e);    
  }
}

以下は、同じ値を持っているにもかかわらず同等ではない2 つの を示す完全な例です。error_code

#include <boost/asio/error.hpp>
#include <boost/filesystem.hpp>
#include <boost/system/error_code.hpp>

int main()
{
  // Two different error codes.
  boost::system::error_code code1 = make_error_code(
    boost::system::errc::no_such_file_or_directory);
  boost::system::error_code code2 = make_error_code(
    boost::asio::error::host_not_found_try_again);

  // That have different error categories.
  assert(code1.category() != code2.category());
  assert(code1.default_error_condition().category() !=
         code2.default_error_condition().category());

  // Yet have the same value.
  assert(code1.value() == code2.value());
  assert(code1.default_error_condition().value() ==
         code2.default_error_condition().value());

  // Use the comparision operation to check both value
  // and category.
  assert(code1 != code2);
  assert(code1.default_error_condition() !=
         code2.default_error_condition());

  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  // Test with Boost.Filesytem
  try
  {
    boost::filesystem::canonical("bogus_file");
  }
  catch(boost::filesystem::filesystem_error& error)
  {
    if (error.code() == 
        make_error_code(boost::system::errc::no_such_file_or_directory))
    {
      std::cout << "No file or directory" << std::endl;
    }
    if (error.code() ==
        make_error_code(boost::asio::error::host_not_found_try_again))
    {
      std::cout << "Host not found" << std::endl;
    }
  }
}

次の出力が生成されます。

No file or directory
于 2014-05-24T21:49:36.200 に答える