複数のカスタム例外をキャッチしますか?- C++
-
22-09-2019 - |
質問
私は最初の C++ プログラミング クラスの学生で、複数のカスタム例外クラスを作成し、イベント ハンドラーの 1 つで、 try/catch
ブロックしてそれらを適切に処理します。
私の質問は次のとおりです。どうすれば私を捕まえることができますか 複数 私のカスタム例外 try/catch
ブロック? GetMessage()
例外クラスのカスタム メソッドで、例外の説明を 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;
};
解決
あなたが複数の例外タイプを持っている、と例外の階層がありますと仮定した場合(およびすべての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の]参照によってキャッチ
他のヒント
基本例外クラスを作成し、すべての特定の例外をそこから派生させる必要があります。
class BaseException { };
class HourOutOfRangeException : public BaseException { };
class MinuteOutOfRangeException : public BaseException { };
その後、単一の catch ブロックでそれらすべてをキャッチできます。
catch (const BaseException& e) { }
電話できるようにしたい場合は GetMessage
, 、次のいずれかを行う必要があります。
- そのロジックを
BaseException
, 、 または - 作る
GetMessage
の仮想メンバー関数BaseException
そして、派生した各例外クラスでそれをオーバーライドします。
次のような標準ライブラリ例外の 1 つから例外を派生させることも検討できます。 std::runtime_error
そして慣用句を使用します what()
代わりにメンバー関数 GetMessage()
.
仮想メソッドBaseException
を持っている共通の基底クラスGetMessage()
からすべての例外の導出ます。
次にcatch(const BaseException& e)
ます。
私は今日、同様の問題があったが、それは私が私の問題を解決するために私の解決策を必要としなかったが判明しました。正直なところ、私は本当のユースケース(ログ?)を考えることができなかった、と私は私のコードでそれのために多くの使用を見つけることができませんでした。
はとにかく、このタイプのリストを持つアプローチである(C ++ 11が必要)。私は、このアプローチの利点は、カスタム例外のための共通の基底クラスを持ってする必要はありませんということだと思います(多分、STD ::例外を除いては?)。言い換えれば、それはあなたの例外階層への侵入ではありません。
私は知りませんことを、いくつかの微妙な誤差があるかもしれません。
#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.
}
}
。 解決策は、ブーストするから取得されます。これは、コードの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
私は同じ問題に遭遇すると、ここで私がなってしまったものです。
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;
}
私の場合、関数が戻るとき、それは例外を取得していません。私は実際にキャッチ内部で何もする必要はありませんが、試して外に作業を行うことができます。
タグ
#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;
}`