throw.cc 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // -*- mode: c++; coding: utf-8 -*-
  2. /// @file throw.cc
  3. /// @brief Show how to replace ra:: asserts with custom ones.
  4. // (c) Daniel Llorens - 2019
  5. // This library is free software; you can redistribute it and/or modify it under
  6. // the terms of the GNU Lesser General Public License as published by the Free
  7. // Software Foundation; either version 3 of the License, or (at your option) any
  8. // later version.
  9. #include <exception>
  10. #include <string>
  11. #include "ra/format.hh"
  12. struct ra_error: public std::exception
  13. {
  14. std::string s;
  15. template <class ... A> ra_error(A && ... a): s(ra::format(std::forward<A>(a) ...)) {}
  16. virtual char const * what() const throw ()
  17. {
  18. return s.c_str();
  19. }
  20. };
  21. // RA_ASSERT has to be defined before any "ra/" header to override the default definition of RA_ASSERT ("ra/format.hh" is an independent header and doesn't count).
  22. #ifdef RA_ASSERT
  23. #error RA_ASSERT is already defined!
  24. #endif
  25. #define RA_ASSERT( cond, ... ) \
  26. { if (!( cond )) throw ra_error("ra:: assert [" STRINGIZE(cond) "]" __VA_OPT__(,) __VA_ARGS__); }
  27. #include "ra/ra.hh"
  28. #include "ra/test.hh"
  29. #include <iostream>
  30. using std::cout, std::endl, ra::TestRecorder;
  31. int main()
  32. {
  33. TestRecorder tr(cout);
  34. bool yes = false;
  35. ra::Big<int> a({2, 3}, 9);
  36. std::string msg;
  37. try {
  38. cout << a(2, 3) << endl;
  39. } catch (ra_error & e) {
  40. msg = e.what();
  41. yes = true;
  42. }
  43. tr.info(msg).test(yes);
  44. return tr.summary();
  45. }