use eoExceptions everywhere

This commit is contained in:
Johann Dreo 2020-03-27 00:21:52 +01:00
commit eba2e14950
127 changed files with 524 additions and 418 deletions

View file

@ -59,7 +59,7 @@ edoFileSnapshot::edoFileSnapshot(std::string dirname,
if ( (res == -1) || (res == 127) ) if ( (res == -1) || (res == 127) )
{ {
throw std::runtime_error("Problem executing test of dir in eoFileSnapshot"); throw eoSystemError(s, res);
} }
// now make sure there is a dir without any genXXX file in it // now make sure there is a dir without any genXXX file in it
@ -112,8 +112,8 @@ eoMonitor& edoFileSnapshot::operator()(void)
if (!os) if (!os)
{ {
std::string str = "edoFileSnapshot: Could not open " + _currentFileName; // std::string str = "edoFileSnapshot: Could not open " + _currentFileName;
throw std::runtime_error(str); throw eoFileError(_currentFileName);
} }
if ( _saveFilenames ) if ( _saveFilenames )

View file

@ -30,6 +30,7 @@
#include <stdexcept> // std::runtime_error #include <stdexcept> // std::runtime_error
#include "eoObject.h" // eoObject #include "eoObject.h" // eoObject
#include "eoPersistent.h" // eoPersistent #include "eoPersistent.h" // eoPersistent
#include "eoExceptions.h"
/** /**
@defgroup Core Core components @defgroup Core Core components
@ -73,13 +74,14 @@ public:
/// Return fitness value. /// Return fitness value.
const Fitness& fitness() const { const Fitness& fitness() const {
if (invalid()) if (invalid())
throw std::runtime_error("invalid fitness"); throw eoInvalidFitnessError("Cannot retrieve unevaluated fitness");
return repFitness; return repFitness;
} }
/// Get fitness as reference, useful when fitness is set in a multi-stage way, e.g., MOFitness gets performance information, is subsequently ranked /// Get fitness as reference, useful when fitness is set in a multi-stage way, e.g., MOFitness gets performance information, is subsequently ranked
Fitness& fitnessReference() { Fitness& fitnessReference() {
if (invalid()) throw std::runtime_error("invalid fitness"); if (invalid())
throw eoInvalidFitnessError("Cannot retrieve unevaluated fitness reference");
return repFitness; return repFitness;
} }
@ -120,7 +122,7 @@ public:
* The read and print methods should be compatible and have the same format. * The read and print methods should be compatible and have the same format.
* In principle, format is "plain": they just print a number * In principle, format is "plain": they just print a number
* @param _is a std::istream. * @param _is a std::istream.
* @throw runtime_std::exception If a valid object can't be read. * @throw eoInvalidFitnessError If a valid object can't be read.
*/ */
virtual void readFrom(std::istream& _is) { virtual void readFrom(std::istream& _is) {

View file

@ -60,7 +60,7 @@ public:
Fitness fitness () const Fitness fitness () const
{ {
if (invalid ()) if (invalid ())
throw std::runtime_error ("invalid fitness in PO.h"); throw eoInvalidFitnessError("invalid fitness in PO.h");
return repFitness; return repFitness;
} }
@ -80,7 +80,7 @@ public:
Fitness best () const Fitness best () const
{ {
if (invalid ()) if (invalid ())
throw std::runtime_error ("invalid best fitness in PO.h"); throw eoInvalidFitnessError("invalid best fitness in PO.h");
return bestFitness; return bestFitness;
} }

View file

@ -183,7 +183,7 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
else else
{ {
std::string stmp = std::string("Invalid selection: ") + ppSelect.first; std::string stmp = std::string("Invalid selection: ") + ppSelect.first;
throw std::runtime_error(stmp.c_str()); throw eoException(stmp.c_str());
} }
_state.storeFunctor(select); _state.storeFunctor(select);
@ -260,7 +260,7 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
} }
else else
{ {
throw std::runtime_error("Sorry, only deterministic tournament available at the moment"); throw eoException("Sorry, only deterministic tournament available at the moment");
} }
} }
ptReplace = new eoMGGReplacement<EOT>(-surviveParents, tSize); ptReplace = new eoMGGReplacement<EOT>(-surviveParents, tSize);
@ -341,7 +341,7 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
} }
else // no replacement recognized else // no replacement recognized
{ {
throw std::runtime_error("Invalid replacement type " + replacementParam.first); throw eoException("Invalid replacement type " + replacementParam.first);
} }
ptReplace = & make_general_replacement<EOT>( ptReplace = & make_general_replacement<EOT>(

View file

@ -120,7 +120,7 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
else // parameter passed by user as DetTour(T) else // parameter passed by user as DetTour(T)
nicheSize = atof(ppSelect.second[0].c_str()); nicheSize = atof(ppSelect.second[0].c_str());
if (_dist == NULL) // no distance if (_dist == NULL) // no distance
throw std::runtime_error("You didn't specify a distance when calling make_algo_scalar and using sharing"); throw eoException("You didn't specify a distance when calling make_algo_scalar and using sharing");
select = new eoSharingSelect<EOT>(nicheSize, *_dist); select = new eoSharingSelect<EOT>(nicheSize, *_dist);
} }
else if (ppSelect.first == std::string("StochTour")) else if (ppSelect.first == std::string("StochTour"))
@ -206,7 +206,7 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
else else
{ {
std::string stmp = std::string("Invalid selection: ") + ppSelect.first; std::string stmp = std::string("Invalid selection: ") + ppSelect.first;
throw std::runtime_error(stmp.c_str()); throw eoException(stmp.c_str());
} }
_state.storeFunctor(select); _state.storeFunctor(select);
@ -282,7 +282,7 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
else else
{ {
std::string stmp = std::string("Invalid replacement: ") + ppReplace.first; std::string stmp = std::string("Invalid replacement: ") + ppReplace.first;
throw std::runtime_error(stmp.c_str()); throw eoException(stmp.c_str());
} }
_state.storeFunctor(replace); _state.storeFunctor(replace);

View file

@ -156,7 +156,7 @@ eoContinue<Indi> & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu
// now check that there is at least one! // now check that there is at least one!
if (!continuator) if (!continuator)
throw std::runtime_error("You MUST provide a stopping criterion"); throw eoException("You MUST provide a stopping criterion");
// OK, it's there: store in the eoState // OK, it's there: store in the eoState
_state.storeFunctor(continuator); _state.storeFunctor(continuator);

View file

@ -97,7 +97,7 @@ eoReduce<EOT> & decode_reduce(eoParamParamType & _ppReduce, eoState & _state)
{ {
p = atof(_ppReduce.second[0].c_str()); p = atof(_ppReduce.second[0].c_str());
if ( (p<=0.5) || (p>1) ) if ( (p<=0.5) || (p>1) )
throw std::runtime_error("Stochastic tournament size should be in [0.5,1]"); throw eoException("Stochastic tournament size should be in [0.5,1]");
} }
ptReduce = new eoStochTournamentTruncate<EOT>(p); ptReduce = new eoStochTournamentTruncate<EOT>(p);
@ -110,7 +110,7 @@ eoReduce<EOT> & decode_reduce(eoParamParamType & _ppReduce, eoState & _state)
} }
else // no known reduction entered else // no known reduction entered
{ {
throw std::runtime_error("Unknown reducer: " + _ppReduce.first); throw eoException("Unknown reducer: " + _ppReduce.first);
} }
// all done, stores and return a reference // all done, stores and return a reference
_state.storeFunctor(ptReduce); _state.storeFunctor(ptReduce);

View file

@ -56,7 +56,7 @@ public:
{ {
// First checks that no other eoCtrlCContinue does exist // First checks that no other eoCtrlCContinue does exist
if (existCtrlCContinue) if (existCtrlCContinue)
throw std::runtime_error("A signal handler for Ctrl C is already defined!\n"); throw eoParamException("A signal handler for Ctrl C is already defined!\n");
#ifndef _WINDOWS #ifndef _WINDOWS
#ifdef SIGQUIT #ifdef SIGQUIT

View file

@ -261,8 +261,8 @@ template<class EOT> class eoEasyEA: public eoAlgo<EOT>
do do
{ {
try // try
{ // {
unsigned pSize = _pop.size(); unsigned pSize = _pop.size();
offspring.clear(); // new offspring offspring.clear(); // new offspring
@ -273,17 +273,17 @@ template<class EOT> class eoEasyEA: public eoAlgo<EOT>
replace(_pop, offspring); // after replace, the new pop. is in _pop replace(_pop, offspring); // after replace, the new pop. is in _pop
if (pSize > _pop.size()) if (pSize > _pop.size())
throw std::runtime_error("Population shrinking!"); throw eoException("Population shrinking!");
else if (pSize < _pop.size()) else if (pSize < _pop.size())
throw std::runtime_error("Population growing!"); throw eoException("Population growing!");
} // }
catch (std::exception& e) // catch (std::exception& e)
{ // {
std::string s = e.what(); // std::string s = e.what();
s.append( " in eoEasyEA"); // s.append( " in eoEasyEA");
throw std::runtime_error( s ); // throw std::runtime_error( s );
} // }
} }
while ( continuator( _pop ) ); while ( continuator( _pop ) );
} }

View file

@ -129,8 +129,8 @@ public:
/// Apply a few iteration of flight to the population (=swarm). /// Apply a few iteration of flight to the population (=swarm).
virtual void operator () (eoPop < POT > &_pop) virtual void operator () (eoPop < POT > &_pop)
{ {
try // try
{ // {
// initializes the topology, velocity, best particle(s) // initializes the topology, velocity, best particle(s)
init(); init();
do do
@ -154,13 +154,13 @@ public:
} }
while (continuator (_pop)); while (continuator (_pop));
} // }
catch (std::exception & e) // catch (std::exception & e)
{ // {
std::string s = e.what (); // std::string s = e.what ();
s.append (" in eoEasyPSO"); // s.append (" in eoEasyPSO");
throw std::runtime_error (s); // throw std::runtime_error (s);
} // }
} }

View file

@ -105,8 +105,8 @@ protected:
} }
#ifndef NDEBUG #ifndef NDEBUG
if ( !_of.is_open() ) { if ( !_of.is_open() ) {
std::string str = "Error, eoEvalDump could not open: " + _filename; // std::string str = "Error, eoEvalDump could not open: " + _filename;
throw std::runtime_error( str ); throw eoFileError( _filename );
} }
#endif #endif
// here, in release mode, we assume that the file could be opened // here, in release mode, we assume that the file could be opened

View file

@ -54,6 +54,69 @@ protected:
const std::string _msg; const std::string _msg;
}; };
class eoInvalidFitnessError : public eoException
{
public:
eoInvalidFitnessError(std::string msg = "Invalid fitness") : eoException(msg) {}
~eoInvalidFitnessError() throw() {}
};
class eoPopSizeException : public eoException
{
public:
eoPopSizeException(size_t size, std::string msg = "") :
eoException(),
_size(size),
_msg(msg)
{}
virtual std::string message() const throw()
{
std::ostringstream oss;
oss << "Bad population size: " << _size;
if(_msg != "") {
oss << ", " << _msg;
}
return oss.str();
}
~eoPopSizeException() throw() {}
protected:
const size_t _size;
const std::string _msg;
};
class eoPopSizeChangeException : public eoPopSizeException
{
public:
eoPopSizeChangeException(size_t size_from, size_t size_to, std::string msg="") :
eoPopSizeException(0),
_size_from(size_from),
_size_to(size_to),
_msg(msg)
{}
virtual std::string message() const throw()
{
std::ostringstream oss;
oss << "Population size changed from " << _size_from << " to " << _size_to;
if(_msg != "") {
oss << ", " << _msg;
}
return oss.str();
}
~eoPopSizeChangeException() throw() {}
protected:
const size_t _size_from;
const size_t _size_to;
const std::string _msg;
};
/** Base class for exceptions which need to stop the algorithm to be handled /** Base class for exceptions which need to stop the algorithm to be handled
* *
* (like stopping criterion or numerical errors). * (like stopping criterion or numerical errors).
@ -110,7 +173,7 @@ public:
virtual std::string message() const throw() virtual std::string message() const throw()
{ {
std::ostringstream msg; std::ostringstream msg;
msg << "STOP because the maximum number of allowed seconds has been reached (" msg << "The maximum number of allowed seconds has been reached ("
<< _elapsed << ")"; << _elapsed << ")";
return msg.str(); return msg.str();
} }
@ -140,7 +203,7 @@ public:
virtual std::string message() const throw() virtual std::string message() const throw()
{ {
std::ostringstream msg; std::ostringstream msg;
msg << " the maximum number of evaluation has been reached (" msg << "The maximum number of evaluation has been reached ("
<< _threshold << ")."; << _threshold << ").";
return msg.str(); return msg.str();
} }
@ -226,7 +289,7 @@ public:
_cmd(cmd), _has_pipe(false), _err_code(-1), _output("") _cmd(cmd), _has_pipe(false), _err_code(-1), _output("")
{ } { }
eoSystemError(std::string cmd, int err_code, std::string output) : eoSystemError(std::string cmd, int err_code, std::string output = "") :
eoException(), eoException(),
_cmd(cmd), _has_pipe(true), _err_code(err_code), _output(output) _cmd(cmd), _has_pipe(true), _err_code(err_code), _output(output)
{ } { }
@ -234,10 +297,12 @@ public:
virtual std::string message() const throw() virtual std::string message() const throw()
{ {
std::ostringstream ss; std::ostringstream ss;
ss << "System call: `" << _cmd << "` error"; ss << "System call: `" << _cmd << "` ended with error";
if(_has_pipe) { if(_has_pipe) {
ss << " code #" << _err_code ss << " code #" << _err_code;
<< " with the following output:" << std::endl << _output; if(_output != "") {
ss << " with the following output:" << std::endl << _output;
}
} }
return ss.str(); return ss.str();
} }
@ -251,4 +316,24 @@ protected:
const std::string _output; const std::string _output;
}; };
class eoFileError : public eoSystemError
{
public:
eoFileError(std::string filename) :
eoSystemError(""),
_filename(filename)
{ }
virtual std::string message() const throw()
{
std::ostringstream oss;
oss << "Could not open file: " << _filename;
return oss.str();
}
protected:
std::string _filename;
};
#endif // __eoExceptions_h__ #endif // __eoExceptions_h__

View file

@ -66,7 +66,7 @@ public :
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw eoException(s);
} }
bool changed = false; bool changed = false;
for ( unsigned i = 0; i < _eo1.size(); i++ ) { for ( unsigned i = 0; i < _eo1.size(); i++ ) {
@ -109,7 +109,7 @@ public :
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw eoException(s);
} }
bool changed = false; bool changed = false;
@ -155,7 +155,7 @@ public :
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw eoException(s);
} }
bool hasChanged = false; bool hasChanged = false;
for (unsigned i=0; i<_eo1.size(); i++) for (unsigned i=0; i<_eo1.size(); i++)
@ -199,7 +199,7 @@ public :
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw eoException(s);
} }
bool hasChanged = false; bool hasChanged = false;
unsigned where = eo::rng.random(_eo1.size()-1); unsigned where = eo::rng.random(_eo1.size()-1);

View file

@ -101,7 +101,7 @@ public :
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw eoException(s);
} }
bool changed = false; bool changed = false;
@ -146,7 +146,7 @@ public :
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw eoException(s);
} }
bool hasChanged = false; bool hasChanged = false;
for (unsigned i=0; i<_eo1.size(); i++) for (unsigned i=0; i<_eo1.size(); i++)
@ -191,7 +191,7 @@ public :
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw eoException(s);
} }
bool hasChanged = false; bool hasChanged = false;
unsigned where = eo::rng.random(_eo1.size()-1); unsigned where = eo::rng.random(_eo1.size()-1);

View file

@ -71,7 +71,7 @@ public:
if (_offspring.size() != toKeep) if (_offspring.size() != toKeep)
{ {
std::cerr << "Les tailles " << _offspring.size() << " " << toKeep << std::endl; std::cerr << "Les tailles " << _offspring.size() << " " << toKeep << std::endl;
throw std::runtime_error("eoG3Replacement: wrong number of remaining offspring"); throw eoException("eoG3Replacement: wrong number of remaining offspring");
} }
// and put back into _parents // and put back into _parents
plus(_offspring, _parents); plus(_offspring, _parents);

View file

@ -33,6 +33,7 @@
#include "eoSTLFunctor.h" #include "eoSTLFunctor.h"
#include "utils/eoRndGenerators.h" #include "utils/eoRndGenerators.h"
#include "utils/rnd_generators.h" // for shuffle method #include "utils/rnd_generators.h" // for shuffle method
#include "eoExceptions.h"
/** /**
@ -134,7 +135,7 @@ typedef typename EOT::AtomType AtomType;
: offset(_minSize), extent(_maxSize - _minSize), init(_init) : offset(_minSize), extent(_maxSize - _minSize), init(_init)
{ {
if (_minSize >= _maxSize) if (_minSize >= _maxSize)
throw std::logic_error("eoInitVariableLength: minSize larger or equal to maxSize"); throw eoException("eoInitVariableLength: minSize larger or equal to maxSize");
} }

View file

@ -67,7 +67,7 @@ public:
if (neighborhoodSize >= _pop.size()){ if (neighborhoodSize >= _pop.size()){
std::string s; std::string s;
s.append (" Invalid neighborhood size in eoLinearTopology "); s.append (" Invalid neighborhood size in eoLinearTopology ");
throw std::runtime_error (s); throw eoException(s);
} }
unsigned howManyNeighborhood=_pop.size()/ neighborhoodSize; unsigned howManyNeighborhood=_pop.size()/ neighborhoodSize;

View file

@ -71,7 +71,7 @@ public:
unsigned toKeep = temp.size(); // how many to keep from merged populations unsigned toKeep = temp.size(); // how many to keep from merged populations
// minimal check // minimal check
if (toKeep < 2) if (toKeep < 2)
throw std::runtime_error("Not enough parents killed in eoMGGReplacement"); throw eoException("Not enough parents killed in eoMGGReplacement");
// select best offspring // select best offspring
typename eoPop<EOT>::iterator it = _offspring.it_best_element(); typename eoPop<EOT>::iterator it = _offspring.it_best_element();

View file

@ -67,13 +67,13 @@ public :
if (_interpret_as_rate) if (_interpret_as_rate)
{ {
if ( (_rate<0) || (_rate>1) ) if ( (_rate<0) || (_rate>1) )
throw std::logic_error("eoElitism: rate shoud be in [0,1]"); throw eoParamException("eoElitism: rate shoud be in [0,1]");
rate = _rate; rate = _rate;
} }
else else
{ {
if (_rate<0) if (_rate<0)
throw std::logic_error("Negative number of offspring in eoElitism!"); throw eoParamException("Negative number of offspring in eoElitism!");
combien = (unsigned int)_rate; combien = (unsigned int)_rate;
if (combien != _rate) if (combien != _rate)
eo::log << eo::warnings << "Warning: Number of guys to merge in eoElitism was rounded" << std::endl; eo::log << eo::warnings << "Warning: Number of guys to merge in eoElitism was rounded" << std::endl;
@ -91,7 +91,7 @@ public :
combienLocal = combien; combienLocal = combien;
if (combienLocal > _pop.size()) if (combienLocal > _pop.size())
throw std::logic_error("Elite larger than population"); throw eoException("Elite larger than population");
std::vector<const EOT*> result; std::vector<const EOT*> result;
_pop.nth_element(combienLocal, result); _pop.nth_element(combienLocal, result);

View file

@ -222,7 +222,7 @@ private :
// Check whether the derived class was nice // Check whether the derived class was nice
if (niche_count.size() != fronts[i].size()) if (niche_count.size() != fronts[i].size())
{ {
throw std::logic_error("eoNDSorting: niche and front should have the same size"); throw eoException("eoNDSorting: niche and front should have the same size");
} }
double max_niche = *std::max_element(niche_count.begin(), niche_count.end()); double max_niche = *std::max_element(niche_count.begin(), niche_count.end());
@ -322,7 +322,7 @@ private :
// Check whether the derived class was nice // Check whether the derived class was nice
if (niche_count.size() != current_front.size()) if (niche_count.size() != current_front.size())
{ {
throw std::logic_error("eoNDSorting: niche and front should have the same size"); throw eoException("eoNDSorting: niche and front should have the same size");
} }
double max_niche = *std::max_element(niche_count.begin(), niche_count.end()); double max_niche = *std::max_element(niche_count.begin(), niche_count.end());

Some files were not shown because too many files have changed in this diff Show more