OSDN Git Service

2011-07-29 Benjamin Kosnik <bkoz@redhat.com>
[pf3gnuchains/gcc-fork.git] / libstdc++-v3 / doc / xml / manual / using_exceptions.xml
1 <section xmlns="http://docbook.org/ns/docbook" version="5.0" 
2          xml:id="manual.intro.using.exceptions" xreflabel="Using Exceptions">
3 <?dbhtml filename="using_exceptions.html"?>
4
5 <info><title>Exceptions</title>
6   <keywordset>
7     <keyword>
8       C++
9     </keyword>
10     <keyword>
11       exception
12     </keyword>
13     <keyword>
14       error
15     </keyword>
16     <keyword>
17       exception neutrality
18     </keyword>
19     <keyword>
20       exception safety
21     </keyword>
22     <keyword>
23       exception propagation
24     </keyword>
25     <keyword>
26       -fno-exceptions
27     </keyword>
28   </keywordset>
29 </info>
30
31 <para>
32 The C++ language provides language support for stack unwinding
33 with <literal>try</literal> and <literal>catch</literal> blocks and
34 the <literal>throw</literal> keyword.
35 </para>
36
37 <para>
38 These are very powerful constructs, and require some thought when
39 applied to the standard library in order to yield components that work
40 efficiently while cleaning up resources when unexpectedly killed via
41 exceptional circumstances.
42 </para>
43
44 <para>
45 Two general topics of discussion follow:
46 exception neutrality and exception safety.
47 </para>
48
49
50 <section xml:id="intro.using.exception.safety" xreflabel="Exception Safety"><info><title>Exception Safety</title></info>
51
52
53   <para>
54     What is exception-safe code?
55   </para>
56
57   <para>
58     Will define this as reasonable and well-defined behavior by classes
59     and functions from the standard library when used by user-defined
60     classes and functions that are themselves exception safe.
61   </para>
62
63   <para>
64     Please note that using exceptions in combination with templates
65     imposes an additional requirement for exception
66     safety. Instantiating types are required to have destructors that
67     do no throw.
68   </para>
69
70   <para>
71     Using the layered approach from Abrahams, can classify library
72     components as providing set levels of safety. These will be called
73     exception guarantees, and can be divided into three categories.
74   </para>
75
76 <itemizedlist>
77
78   <listitem>
79   <para>
80     One. Don't throw.
81   </para>
82   <para>
83     As specified in 23.2.1 general container requirements. Applicable
84     to container and string classes.
85   </para>
86   <para>
87     Member
88     functions <function>erase</function>, <function>pop_back</function>, <function>pop_front</function>, <function>swap</function>, <function>clear</function>. And <type>iterator</type>
89     copy constructor and assignment operator.
90   </para>
91   </listitem>
92
93   <listitem>
94   <para>
95     Two. Don't leak resources when exceptions are thrown. This is
96     also referred to as the <quote>basic</quote> exception safety guarantee.
97   </para>
98
99   <para>
100     This applicable throughout the standard library.
101   </para>
102   </listitem>
103
104   <listitem>
105   <para>
106     Three. Commit-or-rollback semantics.  This is
107     referred to as <quote>strong</quote> exception safety guarantee.
108   </para>
109
110   <para>
111     As specified in 23.2.1 general container requirements. Applicable
112     to container and string classes.
113   </para>
114   <para>
115     Member functions <function>insert</function> of a single
116     element, <function>push_back</function>, <function>push_front</function>,
117     and <function>rehash</function>.
118   </para>
119
120   </listitem>
121 </itemizedlist>
122
123 </section>
124
125
126 <section xml:id="intro.using.exception.propagating" xreflabel="Exceptions Neutrality"><info><title>Exception Neutrality</title></info>
127
128   <para>
129     Simply put, once thrown an exception object should continue in
130     flight unless handled explicitly. In practice, this means
131     propagating exceptions should not be swallowed in
132     gratuitous <literal>catch(...)</literal> blocks. Instead,
133     matching <literal>try</literal> and <literal>catch</literal>
134     blocks should have specific catch handlers and allow un-handed
135     exception objects to propagate. If a
136     terminating <literal>catch(...)</literal> blocks exist then it
137     should end with a <literal>throw</literal> to re-throw the current
138     exception.
139   </para>
140
141   <para>
142     Why do this?
143   </para>
144
145   <para>
146     By allowing exception objects to propagate, a more flexible
147     approach to error handling is made possible (although not
148     required.) Instead of dealing with an error immediately, one can
149     allow the exception to propagate up until sufficient context is
150     available and the choice of exiting or retrying can be made in an
151     informed manner.
152   </para>
153
154   <para>
155     Unfortunately, this tends to be more of a guideline than a strict
156     rule as applied to the standard library. As such, the following is
157     a list of known problem areas where exceptions are not propagated.
158   </para>
159
160 <itemizedlist>
161   <listitem>
162     <para>
163       Input/Output
164     </para>
165   <para>
166     The destructor <function>ios_base::Init::~Init()</function>
167     swallows all exceptions from <function>flush</function> called on
168     all open streams at termination.
169   </para>
170
171   <para>
172     All formatted input in <classname>basic_istream</classname> or
173     formatted output in <classname>basic_ostream</classname> can be
174     configured to swallow exceptions
175     when <function>exceptions</function> is set to
176     ignore <type>ios_base::badbit</type>.
177   </para>
178
179   <para>
180     Functions that have been registered
181     with <function>ios_base::register_callback</function> swallow all
182     exceptions when called as part of a callback event.
183   </para>
184
185   <para>
186     When closing the underlying
187     file, <function>basic_filebuf::close</function> will swallow
188     (non-cancellation) exceptions thrown and return <literal>NULL</literal>.
189   </para>
190   </listitem>
191   <listitem>
192     <para>
193       Thread
194     </para>
195     <para>
196       The constructors of <classname>thread</classname> that take a
197       callable function argument swallow all exceptions resulting from
198       executing the function argument.
199     </para>
200   </listitem>
201 </itemizedlist>
202
203 </section>
204
205 <section xml:id="intro.using.exception.no" xreflabel="-fno-exceptions"><info><title>Doing without</title></info>
206
207   <para>
208     C++ is a language that strives to be as efficient as is possible
209     in delivering features. As such, considerable care is used by both
210     language implementer and designers to make sure unused features
211     not impose hidden or unexpected costs. The GNU system tries to be
212     as flexible and as configurable as possible. So, it should come as
213     no surprise that GNU C++ provides an optional language extension,
214     spelled <literal>-fno-exceptions</literal>, as a way to excise the
215     implicitly generated magic necessary to
216     support <literal>try</literal> and <literal>catch</literal> blocks
217     and thrown objects. (Language support
218     for <literal>-fno-exceptions</literal> is documented in the GNU
219     GCC <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#Code-Gen-Options">manual</link>.)
220   </para>
221
222   <para>Before detailing the library support
223     for <literal>-fno-exceptions</literal>, first a passing note on
224     the things lost when this flag is used: it will break exceptions
225     trying to pass through code compiled
226     with <literal>-fno-exceptions</literal> whether or not that code
227     has any <literal>try</literal> or <literal>catch</literal>
228     constructs. If you might have some code that throws, you shouldn't
229     use <literal>-fno-exceptions</literal>. If you have some code that
230     uses <literal>try</literal> or <literal>catch</literal>, you
231     shouldn't use <literal>-fno-exceptions</literal>.
232   </para>
233
234   <para>
235     And what it to be gained, tinkering in the back alleys with a
236     language like this? Exception handling overhead can be measured
237     in the size of the executable binary, and varies with the
238     capabilities of the underlying operating system and specific
239     configuration of the C++ compiler. On recent hardware with GNU
240     system software of the same age, the combined code and data size
241     overhead for enabling exception handling is around 7%. Of course,
242     if code size is of singular concern than using the appropriate
243     optimizer setting with exception handling enabled
244     (ie, <literal>-Os -fexceptions</literal>) may save up to twice
245     that, and preserve error checking.
246   </para>
247
248   <para>
249     So. Hell bent, we race down the slippery track, knowing the brakes
250     are a little soft and that the right front wheel has a tendency to
251     wobble at speed. Go on: detail the standard library support
252     for <literal>-fno-exceptions</literal>.
253   </para>
254
255   <para>
256     In sum, valid C++ code with exception handling is transformed into
257     a dialect without exception handling. In detailed steps: all use
258     of the C++
259     keywords <literal>try</literal>, <literal>catch</literal>,
260     and <literal>throw</literal> in the standard library have been
261     permanently replaced with the pre-processor controlled equivalents
262     spelled <literal>__try</literal>, <literal>__catch</literal>,
263     and <literal>__throw_exception_again</literal>. They are defined
264     as follows.
265   </para>
266
267 <programlisting>
268 #ifdef __EXCEPTIONS
269 # define __try      try
270 # define __catch(X) catch(X)
271 # define __throw_exception_again throw
272 #else
273 # define __try      if (true)
274 # define __catch(X) if (false)
275 # define __throw_exception_again
276 #endif
277 </programlisting>
278
279 <para>
280   In addition, for every object derived from
281   class <classname>exception</classname>, there exists a corresponding
282   function with C language linkage. An example:
283 </para>
284
285 <programlisting>
286 #ifdef __EXCEPTIONS
287   void __throw_bad_exception(void)
288   { throw bad_exception(); }
289 #else
290   void __throw_bad_exception(void)
291   { abort(); }
292 #endif
293 </programlisting>
294
295 <para>
296   The last language feature needing to be transformed
297   by <literal>-fno-exceptions</literal> is treatment of exception
298   specifications on member functions. Fortunately, the compiler deals
299   with this by ignoring exception specifications and so no alternate
300   source markup is needed.
301 </para>
302
303 <para>
304   By using this combination of language re-specification by the
305   compiler, and the pre-processor tricks and the functional
306   indirection layer for thrown exception objects by the library,
307   libstdc++ files can be compiled
308   with <literal>-fno-exceptions</literal>.
309 </para>
310
311 <para>
312  User code that uses C++ keywords
313  like <literal>throw</literal>, <literal>try</literal>,
314  and <literal>catch</literal> will produce errors even if the user
315  code has included libstdc++ headers and is using constructs
316  like <classname>basic_iostream</classname>. Even though the standard
317  library has been transformed, user code may need modification. User
318   code that attempts or expects to do error checking on standard
319   library components compiled with exception handling disabled should
320   be evaluated and potentially made conditional.
321 </para>
322
323 <para>
324   Some issues remain with this approach (see bugzilla entry
325   25191). Code paths are not equivalent, in
326   particular <literal>catch</literal> blocks are not evaluated. Also
327   problematic are <literal>throw</literal> expressions expecting a
328   user-defined throw handler. Known problem areas in the standard
329   library include using an instance
330   of <classname>basic_istream</classname>
331   with <function>exceptions</function> set to specific
332   <type>ios_base::iostate</type> conditions, or
333   cascading <literal>catch</literal> blocks that dispatch error
334   handling or recovery efforts based on the type of exception object
335   thrown.
336 </para>
337
338 <para>
339   Oh, and by the way: none of this hackery is at all
340   special. (Although perhaps well-deserving of a raised eyebrow.)
341   Support continues to evolve and may change in the future. Similar
342   and even additional techniques are used in other C++ libraries and
343   compilers.
344 </para>
345
346 <para>
347  C++ hackers with a bent for language and control-flow purity have
348   been successfully consoled by grizzled C veterans lamenting the
349   substitution of the C language keyword
350   <literal>const</literal> with the uglified
351   doppelganger <literal>__const</literal>.
352 </para>
353
354
355 </section>
356
357 <section xml:id="intro.using.exception.compat"><info><title>Compatibility</title></info>
358
359
360 <section xml:id="using.exception.compat.c"><info><title>With <literal>C</literal></title></info>
361
362 <para>
363   C language code that is expecting to interoperate with C++ should be
364   compiled with <literal>-fexceptions</literal>. This will make
365   debugging a C language function called as part of C++-induced stack
366   unwinding possible.
367 </para>
368
369 <para>
370   In particular, unwinding into a frame with no exception handling
371 data will cause a runtime abort. If the unwinder runs out of unwind
372 info before it finds a handler, <function>std::terminate()</function>
373 is called.
374 </para>
375
376 <para>
377   Please note that most development environments should take care of
378   getting these details right. For GNU systems, all appropriate parts
379   of the GNU C library are already compiled
380   with <literal>-fexceptions</literal>.
381 </para>
382
383 </section>
384
385 <section xml:id="using.exception.compat.posix"><info><title>With <literal>POSIX</literal> thread cancellation</title></info>
386
387
388 <para>
389   GNU systems re-use some of the exception handling mechanisms to
390   track control flow for <literal>POSIX</literal> thread cancellation.
391 </para>
392
393 <para>
394   Cancellation points are functions defined by POSIX as worthy of
395   special treatment. The standard library may use some of these
396   functions to implement parts of the ISO C++ standard or depend on
397   them for extensions.
398 </para>
399
400 <para>
401   Of note:
402 </para>
403
404 <para>
405   <function>nanosleep</function>,
406   <function>read</function>, <function>write</function>, <function>open</function>, <function>close</function>,
407   and <function>wait</function>.
408 </para>
409
410 <para>
411   The parts of libstdc++ that use C library functions marked as
412   cancellation points should take pains to be exception neutral.
413   Failing this, <literal>catch</literal> blocks have been augmented to
414   show that the POSIX cancellation object is in flight.
415 </para>
416
417 <para>
418   This augmentation adds a <literal>catch</literal> block
419   for <classname>__cxxabiv1::__forced_unwind</classname>, which is the
420   object representing the POSIX cancellation object. Like so:
421 </para>
422
423 <programlisting>
424   catch(const __cxxabiv1::__forced_unwind&amp;)
425   {
426     this-&gt;_M_setstate(ios_base::badbit);
427     throw;
428   }
429   catch(...)
430   { this-&gt;_M_setstate(ios_base::badbit); }
431 </programlisting>
432
433
434 </section>
435 </section>
436
437 <bibliography xml:id="using.exceptions.biblio"><info><title>Bibliography</title></info>
438
439
440   <biblioentry>
441       <title>
442         <link xmlns:xlink="http://www.w3.org/1999/xlink"
443               xlink:href="http://www.opengroup.org/austin">
444         System Interface Definitions, Issue 7 (IEEE Std. 1003.1-2008)
445         </link>
446       </title>
447
448
449     <pagenums>
450       2.9.5 Thread Cancellation
451     </pagenums>
452     <copyright>
453       <year>2008</year>
454       <holder>
455         The Open Group/The Institute of Electrical and Electronics
456         Engineers, Inc.
457       </holder>
458     </copyright>
459   </biblioentry>
460
461   <biblioentry>
462       <title>
463         <link xmlns:xlink="http://www.w3.org/1999/xlink"
464               xlink:href="http://www.boost.org/community/error_handling.html">
465         Error and Exception Handling
466         </link>
467       </title>
468       
469     <author><personname><firstname>David</firstname><surname>Abrahams </surname></personname></author>
470     <publisher>
471       <publishername>
472         Boost
473       </publishername>
474     </publisher>
475   </biblioentry>
476
477
478   <biblioentry>
479       <title>
480         <link xmlns:xlink="http://www.w3.org/1999/xlink"
481               xlink:href="http://www.boost.org/community/exception_safety.html">
482         Exception-Safety in Generic Components
483         </link>
484       </title>
485       
486     <author><personname><firstname>David</firstname><surname>Abrahams</surname></personname></author>
487     <publisher>
488       <publishername>
489         Boost
490       </publishername>
491     </publisher>
492   </biblioentry>
493
494   <biblioentry>
495       <title>
496         <link xmlns:xlink="http://www.w3.org/1999/xlink"
497               xlink:href="www.open-std.org/jtc1/sc22/wg21/docs/papers/1997/N1077.pdf">
498         Standard Library Exception Policy
499         </link>
500       </title>
501
502     <author><personname><firstname>Matt</firstname><surname>Austern</surname></personname></author>
503     <publisher>
504       <publishername>
505         WG21 N1077
506       </publishername>
507     </publisher>
508   </biblioentry>
509
510   <biblioentry>
511       <title>
512         <link xmlns:xlink="http://www.w3.org/1999/xlink"
513               xlink:href="http://gcc.gnu.org/ml/gcc-patches/2001-03/msg00661.html">
514         ia64 c++ abi exception handling
515         </link>
516       </title>
517
518     <author><personname><firstname>Richard</firstname><surname>Henderson</surname></personname></author>
519     <publisher>
520       <publishername>
521         GNU
522       </publishername>
523     </publisher>
524   </biblioentry>
525
526   <biblioentry>
527       <title>
528         <link xmlns:xlink="http://www.w3.org/1999/xlink"
529               xlink:href="http://www.research.att.com/~bs/3rd_safe.pdf">
530         Appendix E: Standard-Library Exception Safety
531         </link>
532       </title>
533     <author><personname><firstname>Bjarne</firstname><surname>Stroustrup</surname></personname></author>
534   </biblioentry>
535
536   <biblioentry>
537     <citetitle>
538       Exceptional C++
539     </citetitle>
540     <pagenums>
541       Exception-Safety Issues and Techniques
542     </pagenums>
543     <author><personname><firstname>Herb</firstname><surname>Sutter</surname></personname></author>
544   </biblioentry>
545
546   <biblioentry>
547       <title>
548         <link xmlns:xlink="http://www.w3.org/1999/xlink"
549               xlink:href="http://gcc.gnu.org/PR25191">
550       GCC Bug 25191: exception_defines.h #defines try/catch
551         </link>
552       </title>
553   </biblioentry>
554
555 </bibliography>
556
557 </section>