2

プログラムが何をしようとしているのかについての情報を例外処理に追加したいと思います。古いコードにはtry、すべてを囲む1 つの大きなブロックがありました。

try {
  read_cfg();  // a sub call might throw runtime_error
  operation1();
  operation2();
}
catch (std::exception& e) {
  std::cerr
    << "Error: " << e.what() << ", "
    // FIXME: also show what we were trying to do
    // FIXME: and what a user could try
    << "\n";
}

エラー メッセージの例:

Error: file "foo.cfg" not found, while reading configuration.
Please make sure the file exists.

try-block を 3 つのブロックに変換しましたが、これは奇妙に感じます。

try {
  read_cfg();  // a sub call might throw runtime_error
}
catch (std::exception& e) {
  std::cerr
    << "Error: " << e.what() << ", "
    << "while reading configuration."
    << "\n";
}
try {
  operation1();
}
catch (std::exception& e) {
  std::cerr
    << "Error: " << e.what() << ", "
    << "while performing operation 1."
    << "\n";
}
try {
  operation2();
}
catch (std::exception& e) {
  std::cerr
    << "Error: " << e.what() << ", "
    << "while performing operation 2."
    << "\n";
}

また、呼び出しごとに 1 つの例外クラスを導入しようとしました ( read_cfg_exceptionoperation1_exceptionoperation2_exception)。read_cfg() では への呼び出し openがスローされる可能性があるため、その例外をキャッチして に変換します read_cfg_exception。これにより、「構成の読み取り中に」問題が発生した場合の追加情報が保存されます。しかし、これも正しくありません。

class read_cfg_exception;
void open(std::string name); // might throw std::runtime_error

void read_cfg()
{
  try {
    open("foo.cfg");
  }
  catch (std::runtime_error& e) {
    throw read_cfg_exception(e.what() + "while reading configuration");
  }
}

そのため、質問があります。エラーが発生したときにプログラムが行っていたことの追加情報を表示するのに適したパターンは何ですか。

4

1 に答える 1

0

take a look at POCO (c++ library) throwing system, that should answer all your questions, you'll learn a lot from that and many good style rules too. The answare to your question will be really long unfortunately (at least I don't know how to make it short).

Anyway don't implement something that makes your code not readable, in your example code is not readable and then not maintainable wich is not wanted.

于 2012-12-03T11:44:33.960 に答える