throw.cc 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // -*- mode: c++; coding: utf-8 -*-
  2. // ra-ra/examples - Customize ra:: reaction to errors.
  3. // (c) Daniel Llorens - 2019-2024
  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. #endif
  11. #define RA_DO_CHECK 1 // kind of the point here
  12. // "ra/base.hh" doesn't depend directly on RA_ASSERT, so the following override is able to use ra::format.
  13. #include "ra/base.hh"
  14. #include <exception>
  15. struct ra_error: public std::exception
  16. {
  17. std::string s;
  18. template <class ... A> ra_error(A && ... a): s(ra::format(std::forward<A>(a) ...)) {}
  19. virtual char const * what() const throw () { return s.c_str(); }
  20. };
  21. #define RA_ASSERT( cond, ... ) \
  22. { if (!( cond )) [[unlikely]] throw ra_error("ra::", std::source_location::current(), " (" STRINGIZE(cond) ") " __VA_OPT__(,) __VA_ARGS__); }
  23. // The override will be in effect for the rest of ra::.
  24. #include "ra/ra.hh"
  25. #include "ra/test.hh"
  26. #include <iostream>
  27. using std::cout, std::endl, ra::TestRecorder;
  28. int main()
  29. {
  30. TestRecorder tr(cout);
  31. bool yes = false;
  32. ra::Big<int> a({2, 3}, 9);
  33. std::string msg;
  34. try {
  35. cout << a(2, 3) << endl;
  36. } catch (ra_error & e) {
  37. msg = e.what();
  38. yes = true;
  39. }
  40. tr.info(msg).test(yes);
  41. return tr.summary();
  42. }