exception_api.run-fail.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // (C) Copyright 2015 Boost.Test team.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. // See http://www.boost.org/libs/test for the library home page.
  6. //[example_code
  7. #define BOOST_TEST_MODULE example
  8. #include <boost/test/included/unit_test.hpp>
  9. #include <stdexcept>
  10. #include <fstream>
  11. //! Computes the histogram of the words in a text file
  12. class FileWordHistogram
  13. {
  14. public:
  15. //!@throw std::exception if the file does not exist
  16. FileWordHistogram(std::string filename) : is_processed(false), fileStream_(filename) {
  17. if(!fileStream_.is_open()) throw std::runtime_error("Cannot open the file");
  18. }
  19. //! @returns true on success, false otherwise
  20. bool process() {
  21. if(is_processed) return true;
  22. // ...
  23. is_processed = true;
  24. return true;
  25. }
  26. //!@pre process has been called with status success
  27. //!@throw std::logic_error if preconditions not met
  28. std::map<std::string, std::size_t>
  29. result() const {
  30. if(!is_processed)
  31. throw std::runtime_error("\"process\" has not been called or was not successful");
  32. return histogram;
  33. }
  34. private:
  35. bool is_processed;
  36. std::ifstream fileStream_;
  37. std::map<std::string, std::size_t> histogram;
  38. };
  39. BOOST_AUTO_TEST_CASE( test_throw_behaviour )
  40. {
  41. // __FILE__ is accessible, no exception expected
  42. BOOST_REQUIRE_NO_THROW( FileWordHistogram(__FILE__) );
  43. // ".. __FILE__" does not exist, API says std::exception, and implementation
  44. // raises std::runtime_error child of std::exception
  45. BOOST_CHECK_THROW( FileWordHistogram(".." __FILE__), std::exception );
  46. {
  47. FileWordHistogram instance(__FILE__);
  48. // api says "std::logic_error", implementation is wrong.
  49. // std::runtime_error not a child of std::logic_error, not intercepted
  50. // here.
  51. BOOST_CHECK_THROW(instance.result(), std::logic_error);
  52. }
  53. }
  54. //]