throw.cc 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // -*- mode: c++; coding: utf-8 -*-
  2. // ra-ra/examples - Customize ra:: reaction to errors.
  3. // (c) Daniel Llorens - 2019-2023
  4. // This library is free software; you can redistribute it and/or modify it under
  5. // the terms of the GNU Lesser General Public License as published by the Free
  6. // Software Foundation; either version 3 of the License, or (at your option) any
  7. // later version.
  8. #ifdef RA_DO_CHECK
  9. #undef RA_DO_CHECK
  10. #define RA_DO_CHECK 1 // kind of the point here
  11. #endif
  12. #include <exception>
  13. #include <string>
  14. // "ra/bootstrap.hh" doesn't depend directly on RA_ASSERT, so the following override is able to use ra::format.
  15. #include "ra/bootstrap.hh"
  16. struct ra_error: public std::exception
  17. {
  18. std::string s;
  19. template <class ... A> ra_error(A && ... a): s(ra::format(std::forward<A>(a) ...)) {}
  20. virtual char const * what() const throw ()
  21. {
  22. return s.c_str();
  23. }
  24. };
  25. #define RA_ASSERT( cond, ... ) \
  26. { if (!( cond )) throw ra_error("ra:: assert [" STRINGIZE(cond) "] " __VA_OPT__(,) __VA_ARGS__); }
  27. // The override will be in effect for the rest of ra::.
  28. #include "ra/ra.hh"
  29. #include "ra/test.hh"
  30. #include <iostream>
  31. using std::cout, std::endl, ra::TestRecorder;
  32. int main()
  33. {
  34. TestRecorder tr(cout);
  35. bool yes = false;
  36. ra::Big<int> a({2, 3}, 9);
  37. std::string msg;
  38. try {
  39. cout << a(2, 3) << endl;
  40. } catch (ra_error & e) {
  41. msg = e.what();
  42. yes = true;
  43. }
  44. tr.info(msg).test(yes);
  45. return tr.summary();
  46. }