Prendere Più Le Eccezioni Personalizzate?- C++
-
22-09-2019 - |
Domanda
Sono uno studente nel mio primo C++ programmazione di classe, e sto lavorando su un progetto in cui abbiamo per creare più classi di eccezioni personalizzate, e quindi in uno dei nostri gestori di eventi, utilizzare un try/catch
blocco di gestire adeguatamente.
La mia domanda è:Come faccio a prendere il mio più le eccezioni personalizzate nel mio try/catch
blocco? GetMessage()
è un metodo personalizzato nelle mie classi di eccezione che restituisce l'eccezione spiegazione come un std::string
.Qui di seguito ho compreso tutto il codice in questione dal mio progetto.
Grazie per il vostro aiuto!
blocco try/catch
// 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);;
}
Metodo 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!");
}
Solo uno dei miei classi di eccezioni personalizzate, gli altri hanno la stessa struttura come questa
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;
};
Soluzione
Se si dispone di più tipi di eccezione, e supponendo che non c'è una gerarchia di eccezioni (e tutti i derivati pubblicamente da una sottoclasse di std::exception
,) iniziare dalla più specifica e continua per più generale:
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
}
D'altra parte, se siete interessati solo il messaggio di errore - throw
stessa eccezione, dire std::runtime_error
con messaggi diversi, e quindi catch
che:
try
{
// code throws some subclass of std::exception
}
catch ( const std::exception& e )
{
std::cerr << "ERROR: " << e.what() << std::endl;
}
Ricordo anche - gettare valore di cattura per [const] di riferimento.
Altri suggerimenti
Si dovrebbe creare una base eccezione di classe e di avere tutte le vostre specifiche eccezioni da essa derivano:
class BaseException { };
class HourOutOfRangeException : public BaseException { };
class MinuteOutOfRangeException : public BaseException { };
È quindi possibile prendere tutti loro in un unico blocco catch:
catch (const BaseException& e) { }
Se si vuole essere in grado di chiamare GetMessage
, avrete bisogno di:
- posto che la logica in
BaseException
, o - fare
GetMessage
una funzione membro virtual inBaseException
e di sostituire in ogni derivato classi di eccezione.
Si potrebbe anche considerare di avere delle eccezioni derivare da una di libreria standard eccezioni, come std::runtime_error
e utilizzare il idiomatiche what()
funzione membro invece di GetMessage()
.
Derivano tutti i tuoi eccezioni da una classe base comune BaseException
che ha un metodo virtuale GetMessage()
.
Quindi catch(const BaseException& e)
.
Ho avuto un simile problema di oggi, ma si è rivelato non ho bisogno che la mia soluzione per risolvere il mio problema.Onestamente, non riesco a pensare a veri casi di utilizzo (registrazione?), e non riesco a trovare molto uso nel mio codice.
Comunque, questo è un approccio di tipo list (richiede C++11).Penso che il vantaggio di questo approccio è che non c'è bisogno di avere una classe base comune per le eccezioni personalizzate (tranne che per std::exception, forse?).In altre parole, non è invadente per la tua gerarchia di eccezioni.
Ci potrebbero essere alcuni piccoli errori che io non sono a conoscenza.
#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.
}
}
Quando i modelli non possono, macro salvare il giorno.La soluzione è preso da Boost.Bolle di 7 righe di codice.
/// @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
Mi sono scontrato con lo stesso problema e qui è quello che ho finito con:
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;
}
Nel mio caso la funzione restituisce quando non ottiene un'eccezione.Quindi io in realtà non hanno a che fare nulla all'interno della cattura, ma non possono fare il lavoro al di fuori della specialità.
#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;
}`