66

私は最初のC++プログラミングクラスの学生であり、複数のカスタム例外クラスを作成する必要があるプロジェクトに取り組んでいます。次に、イベントハンドラーの1つで、try/catchブロックを使用してそれらを適切に処理します。

私の質問は、ブロック内の複数のカスタム例外をキャッチするにはどうすればよいですか?は例外クラスのカスタムメソッドであり、例外の説明を。として返します。以下に、プロジェクトの関連するすべてのコードを含めました。try/catchGetMessage()std::string

ご協力いただきありがとうございます!

トライ/キャッチブロック


    // This is in one of my event handlers, newEnd is a wxTextCtrl
try {
    first.ValidateData();
    newEndT = first.ComputeEndTime();
    *newEnd << newEndT;
}
catch (// don't know what do to here) {
    wxMessageBox(_(e.GetMessage()), 
                 _("Something Went Wrong!"),
                 wxOK | wxICON_INFORMATION, this);;
}

ValidateData()メソッド


void Time::ValidateData()
{
    int startHours, startMins, endHours, endMins;

    startHours = startTime / MINUTES_TO_HOURS;
    startMins = startTime % MINUTES_TO_HOURS;
    endHours = endTime / MINUTES_TO_HOURS;
    endMins = endTime % MINUTES_TO_HOURS;

    if (!(startHours <= HOURS_MAX && startHours >= HOURS_MIN))
        throw new HourOutOfRangeException("Beginning Time Hour Out of Range!");
    if (!(endHours <= HOURS_MAX && endHours >= HOURS_MIN))
        throw new HourOutOfRangeException("Ending Time Hour Out of Range!");
    if (!(startMins <= MINUTE_MAX && startMins >= MINUTE_MIN))
        throw new MinuteOutOfRangeException("Starting Time Minute Out of    Range!");
    if (!(endMins <= MINUTE_MAX && endMins >= MINUTE_MIN))
        throw new MinuteOutOfRangeException("Ending Time Minute Out of Range!");
    if(!(timeDifference <= P_MAX && timeDifference >= P_MIN))
        throw new PercentageOutOfRangeException("Percentage Change Out of Range!");
    if (!(startTime < endTime))
        throw new StartEndException("Start Time Cannot Be Less Than End Time!");
}

私のカスタム例外クラスの1つだけで、他のクラスはこれと同じ構造を持っています


class HourOutOfRangeException
{
public:
        // param constructor
        // initializes message to passed paramater
        // preconditions - param will be a string
        // postconditions - message will be initialized
        // params a string
        // no return type
        HourOutOfRangeException(string pMessage) : message(pMessage) {}
        // GetMessage is getter for var message
        // params none
        // preconditions - none
        // postconditions - none
        // returns string
        string GetMessage() { return message; }
        // destructor
        ~HourOutOfRangeException() {}
private:
        string message;
};
4

8 に答える 8

82

複数の例外タイプがあり、例外の階層があると仮定した場合(および、すべてがのサブクラスから公に派生したstd::exception場合)、最も具体的なものから始めて、より一般的なものに進みます。

try
{
    // throws something
}
catch ( const MostSpecificException& e )
{
    // handle custom exception
}
catch ( const LessSpecificException& e )
{
    // handle custom exception
}
catch ( const std::exception& e )
{
    // standard exceptions
}
catch ( ... )
{
    // everything else
}

一方、エラーメッセージだけに関心がある場合は、throw同じ例外、たとえばstd::runtime_error別のメッセージを使用して、次のcatchようにします。

try
{
    // code throws some subclass of std::exception
}
catch ( const std::exception& e )
{
    std::cerr << "ERROR: " << e.what() << std::endl;
}

また、覚えておいてください-値でスローし、[const]参照でキャッチします。

于 2010-03-25T03:51:32.200 に答える
12

基本例外クラスを作成し、それからすべての特定の例外を派生させる必要があります。

class BaseException { };
class HourOutOfRangeException : public BaseException { };
class MinuteOutOfRangeException : public BaseException { };

次に、それらすべてを1つのキャッチブロックでキャッチできます。

catch (const BaseException& e) { }

電話をかけたい場合はGetMessage、次のいずれかを行う必要があります。

  • そのロジックを、、BaseExceptionまたはに配置します
  • GetMessageで仮想メンバー関数を作成BaseExceptionし、派生した各例外クラスでそれをオーバーライドします。

std::runtime_errorまた、の代わりに慣用的なwhat()メンバー関数を使用するなど、標準ライブラリの例外の1つから例外を派生させることを検討することもできますGetMessage()

于 2010-03-25T03:40:37.680 に答える
1

テンプレートができない場合、マクロはその日を節約します。解決策はBoostから取得されます。要約すると、7行のコードになります。

/// @file multicatch.hpp
#include <boost/preprocessor/variadic/to_list.hpp>
#include <boost/preprocessor/list/for_each.hpp>

/// Callers must define CATCH_BODY(err) to handle the error,
/// they can redefine the CATCH itself, but it is not as convenient. 
#define CATCH(R, _, T) \
  catch (T & err) {    \
    CATCH_BODY(err)    \
  }
/// Generates catches for multiple exception types
/// with the same error handling body.
#define MULTICATCH(...) \
  BOOST_PP_LIST_FOR_EACH(CATCH, _, BOOST_PP_VARIADIC_TO_LIST(__VA_ARGS__))
// end of file multicatch.hpp

/// @file app.cc
#include "multicatch.hpp"

// Contrived example.
/// Supply the error handling logic.
#define CATCH_BODY(err)                        \
  log() << "External failure: " << err.what(); \
  throw;

void foo() {
  try {
    bar();  // May throw three or more sibling or unrelated exceptions.
  }
  MULTICATCH(IOError, OutOfMemory)
}

#undef CATCH_BODY
于 2016-09-11T22:32:04.630 に答える
0

BaseException仮想メソッドを持つ共通の基本クラスからすべての例外を取得しますGetMessage()

次にcatch(const BaseException& e)

于 2010-03-25T03:39:05.757 に答える
0

今日も同様の問題が発生しましたが、問題を解決するための解決策は必要ないことがわかりました。正直なところ、実際のユースケース(ロギング?)は考えられず、コードではあまり使用されていませんでした。

とにかく、これはタイプリストを使用したアプローチです(C ++ 11が必要です)。このアプローチの利点は、カスタム例外(std :: exceptionを除く)に共通の基本クラスを用意する必要がないことだと思います。つまり、例外階層に影響を与えることはありません。

私が気付いていない微妙なエラーがあるかもしれません。

#include <type_traits>
#include <exception>

/// Helper class to handle multiple specific exception types
/// in cases when inheritance based approach would catch exceptions
/// that are not meant to be caught.
///
/// If the body of exception handling code is the same
/// for several exceptions,
/// these exceptions can be joined into one catch.
///
/// Only message data of the caught exception is provided.
///
/// @tparam T  Exception types.
/// @tparam Ts  At least one more exception type is required.
template <class T, class... Ts>
class MultiCatch;

/// Terminal case that holds the message.
/// ``void`` needs to be given as terminal explicitly.
template <>
class MultiCatch<void> {
 protected:
  explicit MultiCatch(const char* err_msg) : msg(err_msg) {}
  const char* msg;
};

template <class T, class... Ts>
class MultiCatch : public MultiCatch<Ts...> {
  static_assert(std::is_base_of<std::exception, T>::value, "Not an exception");

 public:
  using MultiCatch<Ts...>::MultiCatch;

  /// Implicit conversion from the guest exception.
  MultiCatch(const T& error) : MultiCatch<Ts...>(error.what()) {}  // NOLINT

  /// @returns The message of the original exception.
  const char* what() const noexcept {
    return MultiCatch<void>::msg;
  }
};

/// To avoid explicit ``void`` in the type list.
template <class... Ts>
using OneOf = MultiCatch<Ts..., void>;

/// Contrived example.
void foo() {
  try {
    bar();  // May throw three or more sibling or unrelated exceptions.
  } catch (const OneOf<IOError, OutOfMemory>& err) {
    log() << "External failure: " << err.what();

    throw;  // Throw the original exception.
  }
}
于 2016-09-11T12:15:19.777 に答える
0

私は同じ問題に遭遇し、これが私が最終的に得たものです:

  std::shared_ptr<MappedImage> MappedImage::get(const std::string & image_dir,
                                                const std::string & name,
                                                const Packet::Checksum & checksum) {
    try {
      return std::shared_ptr<MappedImage>(images_.at(checksum));
    } catch (std::out_of_range) {
    } catch (std::bad_weak_ptr) {
    }
    std::shared_ptr<MappedImage> img =
      std::make_shared<MappedImage>(image_dir, name, checksum);
    images_[checksum_] = img;
    return img;
  }

私の場合、関数は例外を受け取らなかったときに戻ります。だから私は実際にキャッチの中で何もする必要はありませんが、トライの外で仕事をすることができます。

于 2019-01-28T13:15:24.967 に答える
0

例外のクラス階層を制御できず、catchブロックの内容を複製できない場合にこの問題を解決する別の方法は、次のように使用することですdynamic_cast

try
{
   ...
}
catch (std::exception& e)
{
    if(   nullptr == dynamic_cast<exception_type_1*> (&e)
       && nullptr == dynamic_cast<exception_type_2*> (&e))
    {
        throw;
    }
    // here you process the expected exception types
}
于 2021-11-23T14:54:28.900 に答える
-6

#include <iostream> void test(int x)` { try{ if(x==1) throw (1); else if(x==2) throw (2.0); } catch(int a) { cout<<"It's Integer"; } catch(double b) { cout<<"it's Double"; } } int main(){ cout<<" x=1"; test(1); cout<<"X=2"; test(2.0); return 0; }`
于 2018-02-27T11:33:44.830 に答える