try_catch.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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/config.hpp>
  8. #ifdef BOOST_NO_CXX11_VARIADIC_MACROS
  9. # error "variadic macros required"
  10. #else
  11. #include <boost/scope_exit.hpp>
  12. #include <boost/typeof/typeof.hpp>
  13. #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
  14. #include <iostream>
  15. struct file {
  16. file(void) : open_(false) {}
  17. file(char const* path) : open_(false) { open(path); }
  18. void open(char const* path) { open_ = true; }
  19. void close(void) { open_ = false; }
  20. bool is_open(void) const { return open_; }
  21. private:
  22. bool open_;
  23. };
  24. BOOST_TYPEOF_REGISTER_TYPE(file)
  25. void bad(void) {
  26. //[try_catch_bad
  27. file passwd;
  28. try {
  29. passwd.open("/etc/passwd");
  30. // ...
  31. passwd.close();
  32. } catch(...) {
  33. std::clog << "could not get user info" << std::endl;
  34. if(passwd.is_open()) passwd.close();
  35. throw;
  36. }
  37. //]
  38. }
  39. void good(void) {
  40. //[try_catch_good
  41. try {
  42. file passwd("/etc/passwd");
  43. BOOST_SCOPE_EXIT(&passwd) {
  44. passwd.close();
  45. } BOOST_SCOPE_EXIT_END
  46. } catch(...) {
  47. std::clog << "could not get user info" << std::endl;
  48. throw;
  49. }
  50. //]
  51. }
  52. int main(void) {
  53. bad();
  54. good();
  55. return 0;
  56. }
  57. #endif // variadic macros