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

source code of boost/libs/scope_exit/example/try_catch_seq.cpp