Ne.app NeANT
The Ne.app NeANT User module of the NeANT distribution.
rwexcept.cpp
Go to the documentation of this file.
1
30#include <exception> // for exception
31#include <iostream> // for cerr
32#include <vector> // for vector
33#include <cstdlib> // for exit()
34
35#include <rw/_error.h> // for __rw_throw_proc, _RWSTD_ERROR_BAD_CAST
36
37#include <examples.h>
38
39
40// function called from within the library to throw an exception
41void exception_handler (int id, char *what)
42{
43 std::cerr << "exception #" << id << ": " << what << '\n';
44
45 // free what buffer
46 if (what)
47 __rw::__rw_free_what_buf (what);
48
49 // a real program would call abort() here to prevent the potentially
50 // dangerous destruction of objects with static storage duration
51 // abort ();
52
53 // introduce exit into the current scope if it's declared in namespace
54 // std (as it should be) to allow referring to the function without
55 // qualification when <cstdlib> incorrectly declares it at file scope
56 using namespace std;
57
58 // successfully exit the process
59 exit (0);
60
61 // return at your own risk
62}
63
64
65// prevent the allocation of more than 4 elements
66struct Allocator: std::allocator<int>
67{
69 return 4;
70 }
71};
72
73
74int main ()
75{
76 typedef std::vector<int, Allocator> Vector;
77
78 Vector v;
79
80 for (Vector::size_type n = 0; n != 2 * v.max_size (); ++n) {
81 try {
82 // try to reserve storage for `n' values
83 v.reserve (n);
84 }
85 catch (std::exception &e) {
86 std::cerr << "caught an exception:" << e.what () << '\n';
87
88 // after the first exception has been caught
89 // replace the default throw procedure used
90 // by the library with a user-defined exception
91 // function and continue to iterate
92 __rw::__rw_throw_proc = exception_handler;
93 }
94 }
95
96 // should not reach
97 std::cerr << "unexpected return from main\n";
98
99 return 1;
100}
#define e
Definition 17.names.cpp:118
#define v
Definition 17.names.cpp:138
#define n
Definition 17.names.cpp:130
std::vector< UserClass, std::allocator< UserClass > > Vector
Definition json.h:5363
void exception_handler(int id, char *what)
Definition rwexcept.cpp:41
int main()
Definition rwexcept.cpp:74
std::size_t size_type
size_type max_size() const
Definition rwexcept.cpp:68