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"?>
5 <info><title>Exceptions</title>
8 <keyword>exception</keyword>
9 <keyword>error</keyword>
10 <keyword>exception neutrality</keyword>
11 <keyword>exception safety</keyword>
12 <keyword>exception propagation</keyword>
13 <keyword>-fno-exceptions</keyword>
18 The C++ language provides language support for stack unwinding
19 with <literal>try</literal> and <literal>catch</literal> blocks and
20 the <literal>throw</literal> keyword.
24 These are very powerful constructs, and require some thought when
25 applied to the standard library in order to yield components that work
26 efficiently while cleaning up resources when unexpectedly killed via
27 exceptional circumstances.
31 Two general topics of discussion follow:
32 exception neutrality and exception safety.
36 <section xml:id="intro.using.exception.safety" xreflabel="Exception Safety"><info><title>Exception Safety</title></info>
40 What is exception-safe code?
44 Will define this as reasonable and well-defined behavior by classes
45 and functions from the standard library when used by user-defined
46 classes and functions that are themselves exception safe.
50 Please note that using exceptions in combination with templates
51 imposes an additional requirement for exception
52 safety. Instantiating types are required to have destructors that
57 Using the layered approach from Abrahams, can classify library
58 components as providing set levels of safety. These will be called
59 exception guarantees, and can be divided into three categories.
69 As specified in 23.2.1 general container requirements. Applicable
70 to container and string classes.
74 functions <function>erase</function>, <function>pop_back</function>, <function>pop_front</function>, <function>swap</function>, <function>clear</function>. And <type>iterator</type>
75 copy constructor and assignment operator.
81 Two. Don't leak resources when exceptions are thrown. This is
82 also referred to as the <quote>basic</quote> exception safety guarantee.
86 This applicable throughout the standard library.
92 Three. Commit-or-rollback semantics. This is
93 referred to as <quote>strong</quote> exception safety guarantee.
97 As specified in 23.2.1 general container requirements. Applicable
98 to container and string classes.
101 Member functions <function>insert</function> of a single
102 element, <function>push_back</function>, <function>push_front</function>,
103 and <function>rehash</function>.
112 <section xml:id="intro.using.exception.propagating" xreflabel="Exceptions Neutrality"><info><title>Exception Neutrality</title></info>
115 Simply put, once thrown an exception object should continue in
116 flight unless handled explicitly. In practice, this means
117 propagating exceptions should not be swallowed in
118 gratuitous <literal>catch(...)</literal> blocks. Instead,
119 matching <literal>try</literal> and <literal>catch</literal>
120 blocks should have specific catch handlers and allow un-handed
121 exception objects to propagate. If a
122 terminating <literal>catch(...)</literal> blocks exist then it
123 should end with a <literal>throw</literal> to re-throw the current
132 By allowing exception objects to propagate, a more flexible
133 approach to error handling is made possible (although not
134 required.) Instead of dealing with an error immediately, one can
135 allow the exception to propagate up until sufficient context is
136 available and the choice of exiting or retrying can be made in an
141 Unfortunately, this tends to be more of a guideline than a strict
142 rule as applied to the standard library. As such, the following is
143 a list of known problem areas where exceptions are not propagated.
152 The destructor <function>ios_base::Init::~Init()</function>
153 swallows all exceptions from <function>flush</function> called on
154 all open streams at termination.
158 All formatted input in <classname>basic_istream</classname> or
159 formatted output in <classname>basic_ostream</classname> can be
160 configured to swallow exceptions
161 when <function>exceptions</function> is set to
162 ignore <type>ios_base::badbit</type>.
166 Functions that have been registered
167 with <function>ios_base::register_callback</function> swallow all
168 exceptions when called as part of a callback event.
172 When closing the underlying
173 file, <function>basic_filebuf::close</function> will swallow
174 (non-cancellation) exceptions thrown and return <literal>NULL</literal>.
182 The constructors of <classname>thread</classname> that take a
183 callable function argument swallow all exceptions resulting from
184 executing the function argument.
191 <section xml:id="intro.using.exception.alloc" xreflabel="Memory allocation for exceptions"><info><title>Memory allocation</title></info>
194 When the program throws an exception the runtime will obtain storage for
195 a <code>__cxa_exception</code> header and the thrown object itself.
196 Libstdc++ will try to use <code>malloc</code> to obtain storage,
197 but provides an emergency buffer to be used if malloc fails,
198 as described by the <link xmlns:xlink="http://www.w3.org/1999/xlink"
199 xlink:href="https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html#imp-emergency">Itanium
200 exception handling ABI</link>.
204 Contrary to the ABI, the libstdc++ emergency buffer is not always 64kB,
205 and does not always allocate 1kB chunks. The buffer is used as a pool for
206 variable-sized allocations, so that it doesn't waste space for smaller
207 exception objects such as <code>std::bad_alloc</code>.
208 The total size of the buffer is scaled appropriately for the target.
209 Specifically it depends on <code>sizeof(void*)</code>, so that a 64-bit
210 system uses a larger pool than a 32-bit system. This is done because for
211 32-bit systems the exception objects (and the exception header) require
212 less space, and core counts and thread counts are typically lower as well.
216 By default, libstdc++ will use <code>malloc</code> to allocate the buffer
218 <xref linkend="manual.intro.setup.configure"/> libstdc++ with the
219 <code>--enable-libstdcxx-static-eh-pool</code> option will make it
220 use a static buffer instead of using <code>malloc</code>.
224 The buffer size is chosen automatically, but can be overridden
225 by configuring with <code>--with-libstdcxx-eh-pool-obj-count=NUM</code>,
226 where <code>NUM</code> is the number of simultaneous allocations that
227 should be supported. The size of the pool will be sufficient for
228 <code>NUM</code> exceptions of <code>6 * sizeof(void*)</code> bytes,
229 plus another <code>NUM</code> exceptions captured in
230 <classname>std::exception_ptr</classname> and rethrown using
231 <code>std::rethrow_exception</code>. The buffer size determined by the
232 obj-count value applies whether the buffer is reserved as static storage
233 or is allocated dynamically.
234 Setting obj-count to zero will disable the pool, so that no emergency
239 For a dynamic buffer, the default size can also be changed at runtime,
240 per-process, via the <literal>GLIBCXX_TUNABLES</literal> environment
242 The <literal>GLIBCXX_TUNABLES</literal> environment variable should be
243 a string of colon-separated <emphasis>name=value</emphasis> pairs. The
244 following names will be recognized, with the specified semantics:
249 <term><code>glibcxx.eh_pool.obj_count</code></term>
251 The number of exception objects to provide space for in the pool.
252 The value must be a non-negative integer and has the same meaning as the
253 <code>--with-libstdcxx-eh-pool-obj-count</code> option for
254 <filename>configure</filename>.
258 <term><code>glibcxx.eh_pool.obj_size</code></term>
260 The expected size of exception objects that the pool might get used for.
261 The value must be a positive integer, and is measured in units of
262 <code>sizeof(void*)</code>. The default value is <literal>6</literal>
263 which is large enough to store any exception type thrown by libstdc++.
264 Exceptions larger than this can still be allocated from the pool,
265 but larger exceptions will exhaust the pool more rapidly.
272 <section xml:id="intro.using.exception.no" xreflabel="-fno-exceptions"><info><title>Doing without</title></info>
275 C++ is a language that strives to be as efficient as is possible
276 in delivering features. As such, considerable care is used by both
277 language implementer and designers to make sure unused features do
278 not impose hidden or unexpected costs. The GNU system tries to be
279 as flexible and as configurable as possible. So, it should come as
280 no surprise that GNU C++ provides an optional language extension,
281 spelled <literal>-fno-exceptions</literal>, as a way to excise the
282 implicitly generated magic necessary to
283 support <literal>try</literal> and <literal>catch</literal> blocks
284 and thrown objects. (Language support
285 for <literal>-fno-exceptions</literal> is documented in the GCC
286 <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#Code-Gen-Options">manual</link>.)
289 <para>Before detailing the library support
290 for <literal>-fno-exceptions</literal>, first a passing note on
291 the things lost when this flag is used: it will break exceptions
292 trying to pass through code compiled
293 with <literal>-fno-exceptions</literal> whether or not that code
294 has any <literal>try</literal> or <literal>catch</literal>
295 constructs. If you might have some code that throws, you shouldn't
296 use <literal>-fno-exceptions</literal>. If you have some code that
297 uses <literal>try</literal> or <literal>catch</literal>, you
298 shouldn't use <literal>-fno-exceptions</literal>.
302 And what is to be gained, tinkering in the back alleys with a
303 language like this? Exception handling overhead can be measured
304 in the size of the executable binary, and varies with the
305 capabilities of the underlying operating system and specific
306 configuration of the C++ compiler. On recent hardware with GNU
307 system software of the same age, the combined code and data size
308 overhead for enabling exception handling is around 7%. Of course,
309 if code size is of singular concern than using the appropriate
310 optimizer setting with exception handling enabled
311 (ie, <literal>-Os -fexceptions</literal>) may save up to twice
312 that, and preserve error checking.
316 So. Hell bent, we race down the slippery track, knowing the brakes
317 are a little soft and that the right front wheel has a tendency to
318 wobble at speed. Go on: detail the standard library support
319 for <literal>-fno-exceptions</literal>.
323 In sum, valid C++ code with exception handling is transformed into
324 a dialect without exception handling. In detailed steps: all use
326 keywords <literal>try</literal>, <literal>catch</literal>,
327 and <literal>throw</literal> in the standard library have been
328 permanently replaced with the pre-processor controlled equivalents
329 spelled <literal>__try</literal>, <literal>__catch</literal>,
330 and <literal>__throw_exception_again</literal>. They are defined
337 # define __catch(X) catch(X)
338 # define __throw_exception_again throw
340 # define __try if (true)
341 # define __catch(X) if (false)
342 # define __throw_exception_again
347 In addition, for most of the classes derived from
348 class <classname>exception</classname>, there exists a corresponding
349 function with C language linkage. An example:
354 void __throw_bad_exception()
355 { throw bad_exception(); }
357 void __throw_bad_exception()
363 The last language feature needing to be transformed
364 by <literal>-fno-exceptions</literal> is treatment of exception
365 specifications on member functions. Fortunately, the compiler deals
366 with this by ignoring exception specifications and so no alternate
367 source markup is needed.
371 By using this combination of language re-specification by the
372 compiler, and the pre-processor tricks and the functional
373 indirection layer for thrown exception objects by the library,
374 libstdc++ files can be compiled
375 with <literal>-fno-exceptions</literal>.
379 User code that uses C++ keywords
380 like <literal>throw</literal>, <literal>try</literal>,
381 and <literal>catch</literal> will produce errors even if the user
382 code has included libstdc++ headers and is using constructs
383 like <classname>basic_iostream</classname>. Even though the standard
384 library has been transformed, user code may need modification. User
385 code that attempts or expects to do error checking on standard
386 library components compiled with exception handling disabled should
387 be evaluated and potentially made conditional.
391 Some issues remain with this approach (see bugzilla entry
392 25191). Code paths are not equivalent, in
393 particular <literal>catch</literal> blocks are not evaluated. Also
394 problematic are <literal>throw</literal> expressions expecting a
395 user-defined throw handler. Known problem areas in the standard
396 library include using an instance
397 of <classname>basic_istream</classname>
398 with <function>exceptions</function> set to specific
399 <type>ios_base::iostate</type> conditions, or
400 cascading <literal>catch</literal> blocks that dispatch error
401 handling or recovery efforts based on the type of exception object
406 Oh, and by the way: none of this hackery is at all
407 special. (Although perhaps well-deserving of a raised eyebrow.)
408 Support continues to evolve and may change in the future. Similar
409 and even additional techniques are used in other C++ libraries and
414 C++ hackers with a bent for language and control-flow purity have
415 been successfully consoled by grizzled C veterans lamenting the
416 substitution of the C language keyword
417 <literal>const</literal> with the uglified
418 doppelganger <literal>__const</literal>.
424 <section xml:id="intro.using.exception.compat"><info><title>Compatibility</title></info>
427 <section xml:id="using.exception.compat.c"><info><title>With <literal>C</literal></title></info>
430 C language code that is expecting to interoperate with C++ should be
431 compiled with <literal>-fexceptions</literal>. This will make
432 debugging a C language function called as part of C++-induced stack
437 In particular, unwinding into a frame with no exception handling
438 data will cause a runtime abort. If the unwinder runs out of unwind
439 info before it finds a handler, <function>std::terminate()</function>
444 Please note that most development environments should take care of
445 getting these details right. For GNU systems, all appropriate parts
446 of the GNU C library are already compiled
447 with <literal>-fexceptions</literal>.
452 <section xml:id="using.exception.compat.posix"><info><title>With <literal>POSIX</literal> thread cancellation</title></info>
456 GNU systems re-use some of the exception handling mechanisms to
457 track control flow for <literal>POSIX</literal> thread cancellation.
461 Cancellation points are functions defined by POSIX as worthy of
462 special treatment. The standard library may use some of these
463 functions to implement parts of the ISO C++ standard or depend on
472 <function>nanosleep</function>,
473 <function>read</function>, <function>write</function>, <function>open</function>, <function>close</function>,
474 and <function>wait</function>.
478 The parts of libstdc++ that use C library functions marked as
479 cancellation points should take pains to be exception neutral.
480 Failing this, <literal>catch</literal> blocks have been augmented to
481 show that the POSIX cancellation object is in flight.
485 This augmentation adds a <literal>catch</literal> block
486 for <classname>__cxxabiv1::__forced_unwind</classname>, which is the
487 object representing the POSIX cancellation object. Like so:
491 catch(const __cxxabiv1::__forced_unwind&)
493 this->_M_setstate(ios_base::badbit);
497 { this->_M_setstate(ios_base::badbit); }
504 <bibliography xml:id="using.exceptions.biblio"><info><title>Bibliography</title></info>
509 <link xmlns:xlink="http://www.w3.org/1999/xlink"
510 xlink:href="http://www.opengroup.org/austin/">
511 System Interface Definitions, Issue 7 (IEEE Std. 1003.1-2008)
517 2.9.5 Thread Cancellation
522 The Open Group/The Institute of Electrical and Electronics
530 <link xmlns:xlink="http://www.w3.org/1999/xlink"
531 xlink:href="https://www.boost.org/community/error_handling.html">
532 Error and Exception Handling
536 <author><personname><firstname>David</firstname><surname>Abrahams </surname></personname></author>
547 <link xmlns:xlink="http://www.w3.org/1999/xlink"
548 xlink:href="https://www.boost.org/community/exception_safety.html">
549 Exception-Safety in Generic Components
553 <author><personname><firstname>David</firstname><surname>Abrahams</surname></personname></author>
563 <link xmlns:xlink="http://www.w3.org/1999/xlink"
564 xlink:href="https://www.open-std.org/jtc1/sc22/wg21/docs/papers/1997/N1077.pdf">
565 Standard Library Exception Policy
569 <author><personname><firstname>Matt</firstname><surname>Austern</surname></personname></author>
579 <link xmlns:xlink="http://www.w3.org/1999/xlink"
580 xlink:href="http://gcc.gnu.org/ml/gcc-patches/2001-03/msg00661.html">
581 ia64 c++ abi exception handling
585 <author><personname><firstname>Richard</firstname><surname>Henderson</surname></personname></author>
595 <link xmlns:xlink="http://www.w3.org/1999/xlink"
596 xlink:href="https://www.stroustrup.com/3rd_safe.pdf">
597 Appendix E: Standard-Library Exception Safety
600 <author><personname><firstname>Bjarne</firstname><surname>Stroustrup</surname></personname></author>
608 Exception-Safety Issues and Techniques
610 <author><personname><firstname>Herb</firstname><surname>Sutter</surname></personname></author>
615 <link xmlns:xlink="http://www.w3.org/1999/xlink"
616 xlink:href="http://gcc.gnu.org/PR25191">
617 GCC Bug 25191: exception_defines.h #defines try/catch
624 <link xmlns:xlink="http://www.w3.org/1999/xlink"
625 xlink:href="https://www.gnu.org/software/libc/manual/html_node/Tunables.html">
626 Tunables, The GNU C Library