*: Regenerate.
[gcc.git] / libstdc++-v3 / doc / html / manual / using_exceptions.html
1 <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Exceptions</title><meta name="generator" content="DocBook XSL-NS Stylesheets V1.76.1"><meta name="keywords" content="
2 C++
3 ,
4 exception
5 ,
6 error
7 ,
8 exception neutrality
9 ,
10 exception safety
11 ,
12 exception propagation
13 ,
14 -fno-exceptions
15 "><meta name="keywords" content="
16 ISO C++
17 ,
18 library
19 "><meta name="keywords" content="
20 ISO C++
21 ,
22 runtime
23 ,
24 library
25 "><link rel="home" href="../index.html" title="The GNU C++ Library"><link rel="up" href="using.html" title="Chapter 3. Using"><link rel="prev" href="using_concurrency.html" title="Concurrency"><link rel="next" href="debug.html" title="Debugging Support"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Exceptions</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="using_concurrency.html">Prev</a> </td><th width="60%" align="center">Chapter 3. Using</th><td width="20%" align="right"> <a accesskey="n" href="debug.html">Next</a></td></tr></table><hr></div><div class="section" title="Exceptions"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="manual.intro.using.exceptions"></a>Exceptions</h2></div></div></div><p>
26 The C++ language provides language support for stack unwinding
27 with <code class="literal">try</code> and <code class="literal">catch</code> blocks and
28 the <code class="literal">throw</code> keyword.
29 </p><p>
30 These are very powerful constructs, and require some thought when
31 applied to the standard library in order to yield components that work
32 efficiently while cleaning up resources when unexpectedly killed via
33 exceptional circumstances.
34 </p><p>
35 Two general topics of discussion follow:
36 exception neutrality and exception safety.
37 </p><div class="section" title="Exception Safety"><div class="titlepage"><div><div><h3 class="title"><a name="intro.using.exception.safety"></a>Exception Safety</h3></div></div></div><p>
38 What is exception-safe code?
39 </p><p>
40 Will define this as reasonable and well-defined behavior by classes
41 and functions from the standard library when used by user-defined
42 classes and functions that are themselves exception safe.
43 </p><p>
44 Please note that using exceptions in combination with templates
45 imposes an additional requirement for exception
46 safety. Instantiating types are required to have destructors that
47 do no throw.
48 </p><p>
49 Using the layered approach from Abrahams, can classify library
50 components as providing set levels of safety. These will be called
51 exception guarantees, and can be divided into three categories.
52 </p><div class="itemizedlist"><ul class="itemizedlist" type="disc"><li class="listitem"><p>
53 One. Don't throw.
54 </p><p>
55 As specified in 23.2.1 general container requirements. Applicable
56 to container and string classes.
57 </p><p>
58 Member
59 functions <code class="function">erase</code>, <code class="function">pop_back</code>, <code class="function">pop_front</code>, <code class="function">swap</code>, <code class="function">clear</code>. And <span class="type">iterator</span>
60 copy constructor and assignment operator.
61 </p></li><li class="listitem"><p>
62 Two. Don't leak resources when exceptions are thrown. This is
63 also referred to as the <span class="quote"><span class="quote">basic</span></span> exception safety guarantee.
64 </p><p>
65 This applicable throughout the standard library.
66 </p></li><li class="listitem"><p>
67 Three. Commit-or-rollback semantics. This is
68 referred to as <span class="quote"><span class="quote">strong</span></span> exception safety guarantee.
69 </p><p>
70 As specified in 23.2.1 general container requirements. Applicable
71 to container and string classes.
72 </p><p>
73 Member functions <code class="function">insert</code> of a single
74 element, <code class="function">push_back</code>, <code class="function">push_front</code>,
75 and <code class="function">rehash</code>.
76 </p></li></ul></div></div><div class="section" title="Exception Neutrality"><div class="titlepage"><div><div><h3 class="title"><a name="intro.using.exception.propagating"></a>Exception Neutrality</h3></div></div></div><p>
77 Simply put, once thrown an exception object should continue in
78 flight unless handled explicitly. In practice, this means
79 propagating exceptions should not be swallowed in
80 gratuitous <code class="literal">catch(...)</code> blocks. Instead,
81 matching <code class="literal">try</code> and <code class="literal">catch</code>
82 blocks should have specific catch handlers and allow un-handed
83 exception objects to propagate. If a
84 terminating <code class="literal">catch(...)</code> blocks exist then it
85 should end with a <code class="literal">throw</code> to re-throw the current
86 exception.
87 </p><p>
88 Why do this?
89 </p><p>
90 By allowing exception objects to propagate, a more flexible
91 approach to error handling is made possible (although not
92 required.) Instead of dealing with an error immediately, one can
93 allow the exception to propagate up until sufficient context is
94 available and the choice of exiting or retrying can be made in an
95 informed manner.
96 </p><p>
97 Unfortunately, this tends to be more of a guideline than a strict
98 rule as applied to the standard library. As such, the following is
99 a list of known problem areas where exceptions are not propagated.
100 </p><div class="itemizedlist"><ul class="itemizedlist" type="disc"><li class="listitem"><p>
101 Input/Output
102 </p><p>
103 The destructor <code class="function">ios_base::Init::~Init()</code>
104 swallows all exceptions from <code class="function">flush</code> called on
105 all open streams at termination.
106 </p><p>
107 All formatted input in <code class="classname">basic_istream</code> or
108 formatted output in <code class="classname">basic_ostream</code> can be
109 configured to swallow exceptions
110 when <code class="function">exceptions</code> is set to
111 ignore <span class="type">ios_base::badbit</span>.
112 </p><p>
113 Functions that have been registered
114 with <code class="function">ios_base::register_callback</code> swallow all
115 exceptions when called as part of a callback event.
116 </p><p>
117 When closing the underlying
118 file, <code class="function">basic_filebuf::close</code> will swallow
119 (non-cancellation) exceptions thrown and return <code class="literal">NULL</code>.
120 </p></li><li class="listitem"><p>
121 Thread
122 </p><p>
123 The constructors of <code class="classname">thread</code> that take a
124 callable function argument swallow all exceptions resulting from
125 executing the function argument.
126 </p></li></ul></div></div><div class="section" title="Doing without"><div class="titlepage"><div><div><h3 class="title"><a name="intro.using.exception.no"></a>Doing without</h3></div></div></div><p>
127 C++ is a language that strives to be as efficient as is possible
128 in delivering features. As such, considerable care is used by both
129 language implementer and designers to make sure unused features
130 not impose hidden or unexpected costs. The GNU system tries to be
131 as flexible and as configurable as possible. So, it should come as
132 no surprise that GNU C++ provides an optional language extension,
133 spelled <code class="literal">-fno-exceptions</code>, as a way to excise the
134 implicitly generated magic necessary to
135 support <code class="literal">try</code> and <code class="literal">catch</code> blocks
136 and thrown objects. (Language support
137 for <code class="literal">-fno-exceptions</code> is documented in the GNU
138 GCC <a class="link" href="http://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#Code-Gen-Options" target="_top">manual</a>.)
139 </p><p>Before detailing the library support
140 for <code class="literal">-fno-exceptions</code>, first a passing note on
141 the things lost when this flag is used: it will break exceptions
142 trying to pass through code compiled
143 with <code class="literal">-fno-exceptions</code> whether or not that code
144 has any <code class="literal">try</code> or <code class="literal">catch</code>
145 constructs. If you might have some code that throws, you shouldn't
146 use <code class="literal">-fno-exceptions</code>. If you have some code that
147 uses <code class="literal">try</code> or <code class="literal">catch</code>, you
148 shouldn't use <code class="literal">-fno-exceptions</code>.
149 </p><p>
150 And what it to be gained, tinkering in the back alleys with a
151 language like this? Exception handling overhead can be measured
152 in the size of the executable binary, and varies with the
153 capabilities of the underlying operating system and specific
154 configuration of the C++ compiler. On recent hardware with GNU
155 system software of the same age, the combined code and data size
156 overhead for enabling exception handling is around 7%. Of course,
157 if code size is of singular concern than using the appropriate
158 optimizer setting with exception handling enabled
159 (ie, <code class="literal">-Os -fexceptions</code>) may save up to twice
160 that, and preserve error checking.
161 </p><p>
162 So. Hell bent, we race down the slippery track, knowing the brakes
163 are a little soft and that the right front wheel has a tendency to
164 wobble at speed. Go on: detail the standard library support
165 for <code class="literal">-fno-exceptions</code>.
166 </p><p>
167 In sum, valid C++ code with exception handling is transformed into
168 a dialect without exception handling. In detailed steps: all use
169 of the C++
170 keywords <code class="literal">try</code>, <code class="literal">catch</code>,
171 and <code class="literal">throw</code> in the standard library have been
172 permanently replaced with the pre-processor controlled equivalents
173 spelled <code class="literal">__try</code>, <code class="literal">__catch</code>,
174 and <code class="literal">__throw_exception_again</code>. They are defined
175 as follows.
176 </p><pre class="programlisting">
177 #ifdef __EXCEPTIONS
178 # define __try try
179 # define __catch(X) catch(X)
180 # define __throw_exception_again throw
181 #else
182 # define __try if (true)
183 # define __catch(X) if (false)
184 # define __throw_exception_again
185 #endif
186 </pre><p>
187 In addition, for every object derived from
188 class <code class="classname">exception</code>, there exists a corresponding
189 function with C language linkage. An example:
190 </p><pre class="programlisting">
191 #ifdef __EXCEPTIONS
192 void __throw_bad_exception(void)
193 { throw bad_exception(); }
194 #else
195 void __throw_bad_exception(void)
196 { abort(); }
197 #endif
198 </pre><p>
199 The last language feature needing to be transformed
200 by <code class="literal">-fno-exceptions</code> is treatment of exception
201 specifications on member functions. Fortunately, the compiler deals
202 with this by ignoring exception specifications and so no alternate
203 source markup is needed.
204 </p><p>
205 By using this combination of language re-specification by the
206 compiler, and the pre-processor tricks and the functional
207 indirection layer for thrown exception objects by the library,
208 libstdc++ files can be compiled
209 with <code class="literal">-fno-exceptions</code>.
210 </p><p>
211 User code that uses C++ keywords
212 like <code class="literal">throw</code>, <code class="literal">try</code>,
213 and <code class="literal">catch</code> will produce errors even if the user
214 code has included libstdc++ headers and is using constructs
215 like <code class="classname">basic_iostream</code>. Even though the standard
216 library has been transformed, user code may need modification. User
217 code that attempts or expects to do error checking on standard
218 library components compiled with exception handling disabled should
219 be evaluated and potentially made conditional.
220 </p><p>
221 Some issues remain with this approach (see bugzilla entry
222 25191). Code paths are not equivalent, in
223 particular <code class="literal">catch</code> blocks are not evaluated. Also
224 problematic are <code class="literal">throw</code> expressions expecting a
225 user-defined throw handler. Known problem areas in the standard
226 library include using an instance
227 of <code class="classname">basic_istream</code>
228 with <code class="function">exceptions</code> set to specific
229 <span class="type">ios_base::iostate</span> conditions, or
230 cascading <code class="literal">catch</code> blocks that dispatch error
231 handling or recovery efforts based on the type of exception object
232 thrown.
233 </p><p>
234 Oh, and by the way: none of this hackery is at all
235 special. (Although perhaps well-deserving of a raised eyebrow.)
236 Support continues to evolve and may change in the future. Similar
237 and even additional techniques are used in other C++ libraries and
238 compilers.
239 </p><p>
240 C++ hackers with a bent for language and control-flow purity have
241 been successfully consoled by grizzled C veterans lamenting the
242 substitution of the C language keyword
243 <code class="literal">const</code> with the uglified
244 doppelganger <code class="literal">__const</code>.
245 </p></div><div class="section" title="Compatibility"><div class="titlepage"><div><div><h3 class="title"><a name="intro.using.exception.compat"></a>Compatibility</h3></div></div></div><div class="section" title="With C"><div class="titlepage"><div><div><h4 class="title"><a name="using.exception.compat.c"></a>With <code class="literal">C</code></h4></div></div></div><p>
246 C language code that is expecting to interoperate with C++ should be
247 compiled with <code class="literal">-fexceptions</code>. This will make
248 debugging a C language function called as part of C++-induced stack
249 unwinding possible.
250 </p><p>
251 In particular, unwinding into a frame with no exception handling
252 data will cause a runtime abort. If the unwinder runs out of unwind
253 info before it finds a handler, <code class="function">std::terminate()</code>
254 is called.
255 </p><p>
256 Please note that most development environments should take care of
257 getting these details right. For GNU systems, all appropriate parts
258 of the GNU C library are already compiled
259 with <code class="literal">-fexceptions</code>.
260 </p></div><div class="section" title="With POSIX thread cancellation"><div class="titlepage"><div><div><h4 class="title"><a name="using.exception.compat.posix"></a>With <code class="literal">POSIX</code> thread cancellation</h4></div></div></div><p>
261 GNU systems re-use some of the exception handling mechanisms to
262 track control flow for <code class="literal">POSIX</code> thread cancellation.
263 </p><p>
264 Cancellation points are functions defined by POSIX as worthy of
265 special treatment. The standard library may use some of these
266 functions to implement parts of the ISO C++ standard or depend on
267 them for extensions.
268 </p><p>
269 Of note:
270 </p><p>
271 <code class="function">nanosleep</code>,
272 <code class="function">read</code>, <code class="function">write</code>, <code class="function">open</code>, <code class="function">close</code>,
273 and <code class="function">wait</code>.
274 </p><p>
275 The parts of libstdc++ that use C library functions marked as
276 cancellation points should take pains to be exception neutral.
277 Failing this, <code class="literal">catch</code> blocks have been augmented to
278 show that the POSIX cancellation object is in flight.
279 </p><p>
280 This augmentation adds a <code class="literal">catch</code> block
281 for <code class="classname">__cxxabiv1::__forced_unwind</code>, which is the
282 object representing the POSIX cancellation object. Like so:
283 </p><pre class="programlisting">
284 catch(const __cxxabiv1::__forced_unwind&amp;)
285 {
286 this-&gt;_M_setstate(ios_base::badbit);
287 throw;
288 }
289 catch(...)
290 { this-&gt;_M_setstate(ios_base::badbit); }
291 </pre></div></div><div class="bibliography" title="Bibliography"><div class="titlepage"><div><div><h3 class="title"><a name="using.exceptions.biblio"></a>Bibliography</h3></div></div></div><div class="biblioentry" title="System Interface Definitions, Issue 7 (IEEE Std. 1003.1-2008)"><a name="id607142"></a><p><span class="title"><i>
292 <a class="link" href="http://www.opengroup.org/austin" target="_top">
293 System Interface Definitions, Issue 7 (IEEE Std. 1003.1-2008)
294 </a>
295 </i>. </span><span class="pagenums">
296 2.9.5 Thread Cancellation
297 . </span><span class="copyright">Copyright © 2008
298 The Open Group/The Institute of Electrical and Electronics
299 Engineers, Inc.
300 . </span></p></div><div class="biblioentry" title="Error and Exception Handling"><a name="id607173"></a><p><span class="title"><i>
301 <a class="link" href="http://www.boost.org/community/error_handling.html" target="_top">
302 Error and Exception Handling
303 </a>
304 </i>. </span><span class="author"><span class="firstname">David</span> <span class="surname">Abrahams </span>. </span><span class="publisher"><span class="publishername">
305 Boost
306 . </span></span></p></div><div class="biblioentry" title="Exception-Safety in Generic Components"><a name="id607204"></a><p><span class="title"><i>
307 <a class="link" href="http://www.boost.org/community/exception_safety.html" target="_top">
308 Exception-Safety in Generic Components
309 </a>
310 </i>. </span><span class="author"><span class="firstname">David</span> <span class="surname">Abrahams</span>. </span><span class="publisher"><span class="publishername">
311 Boost
312 . </span></span></p></div><div class="biblioentry" title="Standard Library Exception Policy"><a name="id607235"></a><p><span class="title"><i>
313 <a class="link" href="www.open-std.org/jtc1/sc22/wg21/docs/papers/1997/N1077.pdf" target="_top">
314 Standard Library Exception Policy
315 </a>
316 </i>. </span><span class="author"><span class="firstname">Matt</span> <span class="surname">Austern</span>. </span><span class="publisher"><span class="publishername">
317 WG21 N1077
318 . </span></span></p></div><div class="biblioentry" title="ia64 c++ abi exception handling"><a name="id607266"></a><p><span class="title"><i>
319 <a class="link" href="http://gcc.gnu.org/ml/gcc-patches/2001-03/msg00661.html" target="_top">
320 ia64 c++ abi exception handling
321 </a>
322 </i>. </span><span class="author"><span class="firstname">Richard</span> <span class="surname">Henderson</span>. </span><span class="publisher"><span class="publishername">
323 GNU
324 . </span></span></p></div><div class="biblioentry" title="Appendix E: Standard-Library Exception Safety"><a name="id607296"></a><p><span class="title"><i>
325 <a class="link" href="http://www.research.att.com/~bs/3rd_safe.pdf" target="_top">
326 Appendix E: Standard-Library Exception Safety
327 </a>
328 </i>. </span><span class="author"><span class="firstname">Bjarne</span> <span class="surname">Stroustrup</span>. </span></p></div><div class="biblioentry"><a name="id607320"></a><p><span class="citetitle"><em class="citetitle">
329 Exceptional C++
330 </em>. </span><span class="pagenums">
331 Exception-Safety Issues and Techniques
332 . </span><span class="author"><span class="firstname">Herb</span> <span class="surname">Sutter</span>. </span></p></div><div class="biblioentry" title="GCC Bug 25191: exception_defines.h #defines try/catch"><a name="id607340"></a><p><span class="title"><i>
333 <a class="link" href="http://gcc.gnu.org/PR25191" target="_top">
334 GCC Bug 25191: exception_defines.h #defines try/catch
335 </a>
336 </i>. </span></p></div></div></div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="using_concurrency.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="using.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="debug.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Concurrency </td><td width="20%" align="center"><a accesskey="h" href="../index.html">Home</a></td><td width="40%" align="right" valign="top"> Debugging Support</td></tr></table></div></body></html>