Practical C++ Error Handling In Hybrid Environments
by Gigi Sayfan

Example 1:

int main (int argc, char * const argv[]) 
{  
  try
  {
    if (5 != 3)
      throw StreamingException() << 5 << " is not equal to " << 3;
  }
  catch (const StreamingException & e)
  {
    cout << e.what() << endl;
  }
  return 0;
}


Listing One

#ifndef STREAMING_EXCEPTION
#define STREAMING_EXCEPTION

#include <iostream>
#include <sstream>
#include <memory>
#include <stdexcept>

class StreamingException : public std::runtime_error
{
public:
StreamingException() :
  std::runtime_error(""),
  ss_(std::auto_ptr<std::stringstream>
      (new std::stringstream()))
{
}


~StreamingException() throw()
{
}


template <typename T>
StreamingException & operator << (const T & t)
{
  (*ss_) << t;
  return *this;
}


virtual const char * what() const throw()
{
  try
  {
    s_ = ss_->str();
    return s_.c_str();
  }
  catch (...)
  {
   return "StreamingException::what() threw an exception";
  }
}


private:
mutable std::auto_ptr<std::stringstream> ss_;
mutable std::string s_;
};
#endif


