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