Skip to content

Commit

Permalink
Adding basic exception hierarchy
Browse files Browse the repository at this point in the history
  • Loading branch information
Mayeul d'Avezac committed Aug 12, 2015
1 parent cd980ae commit 5c91622
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions cpp/sopt/exception.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#ifndef SOPT_EXCEPTION
#define SOPT_EXCEPTION

#include <exception>
#include <sstream>
#include <string>

namespace sopt {
//! Root exception for sopt
class Exception : public std::exception {

protected:
//! Constructor for derived classes
Exception(std::string const & name, std::string const &filename, size_t lineno)
: std::exception(), message(header(name, filename, lineno)) {}

public:
//! Creates exception
Exception(std::string const &filename, size_t lineno)
: Exception("sopt::Exception", filename, lineno) {}

//! Creates message
const char* what() const noexcept override { return message.c_str(); }

//! Header of the message
static std::string header(
std::string const &name, std::string const &filename, size_t lineno) {
return (std::ostringstream() << name << " at " << filename << ":" << lineno).str();
}

//! Adds to message
template<class OBJECT>
Exception& operator<<(OBJECT const &object) {
message = (std::ostringstream(message) << object).str();
return *this;
}

private:
//! Message to issue
std::string message;
};

# define SOPT_THROW(MSG) throw sopt::Exception(__FILE__, __LINE__) << "\n" << MSG

} /* sopt */
#endif

0 comments on commit 5c91622

Please sign in to comment.