Skip to content

Instantly share code, notes, and snippets.

@j2doll
Created June 15, 2018 00:05
Show Gist options
  • Select an option

  • Save j2doll/d8611fce9c383048a7943211e02e0ccb to your computer and use it in GitHub Desktop.

Select an option

Save j2doll/d8611fce9c383048a7943211e02e0ccb to your computer and use it in GitHub Desktop.
STL exception sample
// STL-exception-sample-example.cpp
// STL exception sample
// How to build:
// 1) gcc
// g++ -lstdc++ main.cpp
// 2) visual studio (visual c++)
// just do it!
//
#include <iostream>
#include <sstream>
#include <memory>
#include <stdexcept>
using namespace std;
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()
{
s_ = ss_->str();
return s_.c_str();
}
private:
mutable std::auto_ptr<std::stringstream> ss_;
mutable std::string s_;
};
int main (int argc, char * const argv[])
{
try
{
if (5 != 3)
throw StreamingException() << 5 << " is not equal to " << 3;
}
catch (const StreamingException & e)
{
cout << " StreamingException : ";
cout << e.what() << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment