How to pass meaningful data to exceptions?

I would like to throw exceptions with a meaningful explanation (socket descriptor, process id, network interface index, ...)! I thought using variable arguments works fine, but lately I realized that it's impossible to extend a class to implement other types of exceptions. So I decided to use std :: ostreamstring as an internal buffer to handle formatting ... but it does not compile! I assume this deals with copy constructors. Anyway, here is my piece of code:  

  class Exception: public std::exception {
public:
  Exception(const char *fmt, ...);
  Exception(const char *fname,
            const char *funcname, int line, const char *fmt, ...);
  //std::ostringstream &Get() { return os_ ; }
  ~Exception() throw();
  virtual const char *what() const throw();

protected: char err_msg_[ERRBUFSIZ]; //std::ostringstream os_; };

The argumens variable constructor cannot be inherited from! that is why i was thinking about std :: ostringstream! Any recommendations on how to implement this approach?

+3
source share
3

..., . va_list. , , :

class Exception: public std::exception {
public:
  Exception(const char *fmt, ...)
  {
    va_list ap;
    va_start(ap, fmt);
    this->init(fmt, ap);
    va_end(ap);
  }

  virtual const char *what() const throw();

protected:
  Exception(); // for use from derived class ctor

  void init(char const* fmt, va_list, ap)
  {
    vsnprintf(err_msg_, sizeof err_msg_, fmt, ap);
  }

  char err_msg_[ERRBUFSIZ];
};

struct Exception2 : Exception
{
  Exception2(const char *fmt, ...)
  {
    va_list ap;
    va_start(ap, fmt);
    this->init(fmt, ap);
    va_end(ap);
  }
};
+2

, , , ostringstream . , , ostringstream be pointer std/boost::shared_ptr? :

#include <exception>
#include <sstream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

struct E : std::exception {
  boost::shared_ptr< std::ostringstream > os_;
  mutable std::string s_;
  std::ostringstream &Get() { return *os_; } 
  const char *what() const throw() {
    s_ = os_->str();
    return s_.c_str();
  }
  E() : os_( boost::make_shared< std::ostringstream >() ) {}
  ~E() throw() {}
};

int main()
{
  try {
    E e;
    e.Get() << "x";
    throw e;
  }
  catch ( std::exception const& e ) {
    cout<< e.what() <<endl;
  }
}

, .

+2

. SocketException .. vararg ... ctor.

, std::ostringstream os_. ostringstream , . std::string.

+2
source

Source: https://habr.com/ru/post/1785720/


All Articles