throw.C 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // -*- mode: c++; coding: utf-8 -*-
  2. /// @file throw.C
  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.H"
  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.H" 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_ARGS__); }
  27. #include "ra/ra.H"
  28. #include "ra/test.H"
  29. #include <iostream>
  30. using std::cout, std::endl;
  31. int main()
  32. {
  33. TestRecorder tr(cout);
  34. bool yes = false;
  35. ra::Big<int> a({2, 3}, 9);
  36. try {
  37. cout << a(2, 3) << endl;
  38. } catch (ra_error & e) {
  39. cout << e.what() << endl;
  40. yes = true;
  41. }
  42. tr.test(yes);
  43. return tr.summary();
  44. }