try_catch_seq.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (C) 2006-2009, 2012 Alexander Nasonov
  2. // Copyright (C) 2012 Lorenzo Caminiti
  3. // Distributed under the Boost Software License, Version 1.0
  4. // (see accompanying file LICENSE_1_0.txt or a copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. // Home at http://www.boost.org/libs/scope_exit
  7. #include <boost/scope_exit.hpp>
  8. #include <boost/typeof/typeof.hpp>
  9. #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
  10. #include <iostream>
  11. struct file {
  12. file(void) : open_(false) {}
  13. file(char const* path) : open_(false) { open(path); }
  14. void open(char const* path) { open_ = true; }
  15. void close(void) { open_ = false; }
  16. bool is_open(void) const { return open_; }
  17. private:
  18. bool open_;
  19. };
  20. BOOST_TYPEOF_REGISTER_TYPE(file)
  21. void bad(void) {
  22. //[try_catch_bad_seq
  23. file passwd;
  24. try {
  25. passwd.open("/etc/passwd");
  26. // ...
  27. passwd.close();
  28. } catch(...) {
  29. std::clog << "could not get user info" << std::endl;
  30. if(passwd.is_open()) passwd.close();
  31. throw;
  32. }
  33. //]
  34. }
  35. void good(void) {
  36. //[try_catch_good_seq
  37. try {
  38. file passwd("/etc/passwd");
  39. BOOST_SCOPE_EXIT( (&passwd) ) {
  40. passwd.close();
  41. } BOOST_SCOPE_EXIT_END
  42. } catch(...) {
  43. std::clog << "could not get user info" << std::endl;
  44. throw;
  45. }
  46. //]
  47. }
  48. int main(void) {
  49. bad();
  50. good();
  51. return 0;
  52. }