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>
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.
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.
45 Two general topics of discussion follow:
46 exception neutrality and exception safety.
50 <section xml:id="intro.using.exception.safety" xreflabel="Exception Safety"><info><title>Exception Safety</title></info>
54 What is exception-safe code?
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.
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
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.
83 As specified in 23.2.1 general container requirements. Applicable
84 to container and string classes.
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.
95 Two. Don't leak resources when exceptions are thrown. This is
96 also referred to as the <quote>basic</quote> exception safety guarantee.
100 This applicable throughout the standard library.
106 Three. Commit-or-rollback semantics. This is
107 referred to as <quote>strong</quote> exception safety guarantee.
111 As specified in 23.2.1 general container requirements. Applicable
112 to container and string classes.
115 Member functions <function>insert</function> of a single
116 element, <function>push_back</function>, <function>push_front</function>,
117 and <function>rehash</function>.
126 <section xml:id="intro.using.exception.propagating" xreflabel="Exceptions Neutrality"><info><title>Exception Neutrality</title></info>
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
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
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.
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.
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>.
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.
186 When closing the underlying
187 file, <function>basic_filebuf::close</function> will swallow
188 (non-cancellation) exceptions thrown and return <literal>NULL</literal>.
196 The constructors of <classname>thread</classname> that take a
197 callable function argument swallow all exceptions resulting from
198 executing the function argument.
205 <section xml:id="intro.using.exception.no" xreflabel="-fno-exceptions"><info><title>Doing without</title></info>
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>.)
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>.
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.
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>.
256 In sum, valid C++ code with exception handling is transformed into
257 a dialect without exception handling. In detailed steps: all use
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
270 # define __catch(X) catch(X)
271 # define __throw_exception_again throw
273 # define __try if (true)
274 # define __catch(X) if (false)
275 # define __throw_exception_again
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:
287 void __throw_bad_exception(void)
288 { throw bad_exception(); }
290 void __throw_bad_exception(void)
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.
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>.
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.
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
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
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>.
357 <section xml:id="intro.using.exception.compat"><info><title>Compatibility</title></info>
360 <section xml:id="using.exception.compat.c"><info><title>With <literal>C</literal></title></info>
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
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>
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>.
385 <section xml:id="using.exception.compat.posix"><info><title>With <literal>POSIX</literal> thread cancellation</title></info>
389 GNU systems re-use some of the exception handling mechanisms to
390 track control flow for <literal>POSIX</literal> thread cancellation.
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
405 <function>nanosleep</function>,
406 <function>read</function>, <function>write</function>, <function>open</function>, <function>close</function>,
407 and <function>wait</function>.
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.
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:
424 catch(const __cxxabiv1::__forced_unwind&)
426 this->_M_setstate(ios_base::badbit);
430 { this->_M_setstate(ios_base::badbit); }
437 <bibliography xml:id="using.exceptions.biblio"><info><title>Bibliography</title></info>
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)
450 2.9.5 Thread Cancellation
455 The Open Group/The Institute of Electrical and Electronics
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
469 <author><personname><firstname>David</firstname><surname>Abrahams </surname></personname></author>
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
486 <author><personname><firstname>David</firstname><surname>Abrahams</surname></personname></author>
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
502 <author><personname><firstname>Matt</firstname><surname>Austern</surname></personname></author>
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
518 <author><personname><firstname>Richard</firstname><surname>Henderson</surname></personname></author>
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
533 <author><personname><firstname>Bjarne</firstname><surname>Stroustrup</surname></personname></author>
541 Exception-Safety Issues and Techniques
543 <author><personname><firstname>Herb</firstname><surname>Sutter</surname></personname></author>
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