fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <stdexcept>
  4.  
  5. template <class Obj, class MemFn, class... Args>
  6. bool throws(const std::string& s, const Obj& obj, MemFn&& memfn, Args&&... args)
  7. {
  8. try
  9. {
  10. (obj.*memfn)(std::forward<Args>(args)...);
  11. std::cout << s << ": " << "Succeeded!!!" << std::endl;
  12. return true;
  13. }
  14. catch (const std::exception& ex)
  15. {
  16. std::cout << s << ": " << "Caught : " << ex.what() << std::endl;
  17. }
  18. catch (...)
  19. {
  20. std::cout << s << ": " << "Caught unknown exception" << std::endl;
  21. }
  22. return false;
  23. }
  24.  
  25. template<typename T>
  26. struct Foo
  27. {
  28. std::string name;
  29.  
  30. int test_fn(T x, T y) const
  31. {
  32. if (y == T())
  33. throw std::out_of_range("Integer division with zero-denominator");
  34.  
  35. return x/y;
  36. }
  37.  
  38. int test_unknown() const
  39. {
  40. throw -1;
  41. }
  42. };
  43.  
  44. int main()
  45. {
  46. Foo<int> foo;
  47. throws("First Test", foo, &Foo<int>::test_fn, 1, 1);
  48. throws("Second Test", foo, &Foo<int>::test_fn, 1, 0);
  49. throws("Third Test", foo, &Foo<int>::test_unknown);
  50. return 0;
  51. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
First Test: Succeeded!!!
Second Test: Caught : Integer division with zero-denominator
Third Test: Caught unknown exception