fork(1) download
  1. #include <iostream>
  2. #include <sstream>
  3.  
  4. template <class exception, class charT, class traits>
  5. std::basic_ostream<charT,traits>& throw_cpp(std::basic_ostream<charT,traits>& os)
  6. {
  7. std::stringstream& self = dynamic_cast<std::stringstream&>(os); //maybe throws std::bad_cast
  8. throw exception(self.str());
  9. return os; //redundant, but the compiler might not know that.
  10. }
  11.  
  12. #include <stdexcept>
  13. #include <fstream>
  14. int main() {
  15. try {
  16. int world = 42;
  17. std::stringstream() << "HELLO " << world << throw_cpp<std::logic_error>;
  18. } catch(const std::logic_error& e) {
  19. std::cerr << e.what() << '\n';
  20. }
  21. try {
  22. std::fstream() << "HELLO " << throw_cpp<std::logic_error>;
  23. } catch(const std::exception& e) {
  24. std::cerr << e.what() << '\n';
  25. }
  26. }
Success #stdin #stdout #stderr 0s 3028KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
HELLO 42
std::bad_cast