<?xml version="1.0" encoding="UTF-8" standalone="no"?><!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 V1.75.2" /><meta name="keywords" content=" C++ , exception , error , exception neutrality , exception safety , exception propagation , -fno-exceptions " /><meta name="keywords" content=" ISO C++ , library " /><link rel="home" href="../spine.html" title="The GNU C++ Library Documentation" /><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><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="sect1" title="Exceptions"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="manual.intro.using.exceptions"></a>Exceptions</h2></div></div></div><p>The C++ language provides language support for stack unwindingwith <code class="literal">try</code> and <code class="literal">catch</code> blocks andthe <code class="literal">throw</code> keyword.</p><p>These are very powerful constructs, and require some thought whenapplied to the standard library in order to yield components that workefficiently while cleaning up resources when unexpectedly killed viaexceptional circumstances.</p><p>Two general topics of discussion follow:exception neutrality and exception safety.</p><div class="sect2" title="Exception Safety"><div class="titlepage"><div><div><h3 class="title"><a id="intro.using.exception.safety"></a>Exception Safety</h3></div></div></div><p>What is exception-safe code?</p><p>Will define this as reasonable and well-defined behavior by classesand functions from the standard library when used by user-definedclasses and functions that are themselves exception safe.</p><p>Please note that using exceptions in combination with templatesimposes an additional requirement for exceptionsafety. Instantiating types are required to have destructors thatdo no throw.</p><p>Using the layered approach from Abrahams, can classify librarycomponents as providing set levels of safety. These will be calledexception guarantees, and can be divided into three categories.</p><div class="itemizedlist"><ul class="itemizedlist" type="disc"><li class="listitem"><p>One. Don't throw.</p><p>As specified in 23.2.1 general container requirements. Applicableto container and string classes.</p><p>Memberfunctions <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>copy constructor and assignment operator.</p></li><li class="listitem"><p>Two. Don't leak resources when exceptions are thrown. This isalso referred to as the <span class="quote">β<span class="quote">basic</span>β</span> exception safety guarantee.</p><p>This applicable throughout the standard library.</p></li><li class="listitem"><p>Three. Commit-or-rollback semantics. This isreferred to as <span class="quote">β<span class="quote">strong</span>β</span> exception safety guarantee.</p><p>As specified in 23.2.1 general container requirements. Applicableto container and string classes.</p><p>Member functions <code class="function">insert</code> of a singleelement, <code class="function">push_back</code>, <code class="function">push_front</code>,and <code class="function">rehash</code>.</p></li></ul></div></div><div class="sect2" title="Exception Neutrality"><div class="titlepage"><div><div><h3 class="title"><a id="intro.using.exception.propagating"></a>Exception Neutrality</h3></div></div></div><p>Simply put, once thrown an exception object should continue inflight unless handled explicitly. In practice, this meanspropagating exceptions should not be swallowed ingratuitous <code class="literal">catch(...)</code> blocks. Instead,matching <code class="literal">try</code> and <code class="literal">catch</code>blocks should have specific catch handlers and allow un-handedexception objects to propagate. If aterminating <code class="literal">catch(...)</code> blocks exist then itshould end with a <code class="literal">throw</code> to re-throw the currentexception.</p><p>Why do this?</p><p>By allowing exception objects to propagate, a more flexibleapproach to error handling is made possible (although notrequired.) Instead of dealing with an error immediately, one canallow the exception to propagate up until sufficient context isavailable and the choice of exiting or retrying can be made in aninformed manner.</p><p>Unfortunately, this tends to be more of a guideline than a strictrule as applied to the standard library. As such, the following isa list of known problem areas where exceptions are not propagated.</p><div class="itemizedlist"><ul class="itemizedlist" type="disc"><li class="listitem"><p>Input/Output</p><p>The destructor <code class="function">ios_base::Init::~Init()</code>swallows all exceptions from <code class="function">flush</code> called onall open streams at termination.</p><p>All formatted input in <code class="classname">basic_istream</code> orformatted output in <code class="classname">basic_ostream</code> can beconfigured to swallow exceptionswhen <code class="function">exceptions</code> is set toignore <span class="type">ios_base::badbit</span>.</p><p>Functions that have been registeredwith <code class="function">ios_base::register_callback</code> swallow allexceptions when called as part of a callback event.</p><p>When closing the underlyingfile, <code class="function">basic_filebuf::close</code> will swallow(non-cancellation) exceptions thrown and return <code class="literal">NULL</code>.</p></li><li class="listitem"><p>Thread</p><p>The constructors of <code class="classname">thread</code> that take acallable function argument swallow all exceptions resulting fromexecuting the function argument.</p></li></ul></div></div><div class="sect2" title="Doing without"><div class="titlepage"><div><div><h3 class="title"><a id="intro.using.exception.no"></a>Doing without</h3></div></div></div><p>C++ is a language that strives to be as efficient as is possiblein delivering features. As such, considerable care is used by bothlanguage implementer and designers to make sure unused featuresnot impose hidden or unexpected costs. The GNU system tries to beas flexible and as configurable as possible. So, it should come asno surprise that GNU C++ provides an optional language extension,spelled <code class="literal">-fno-exceptions</code>, as a way to excise theimplicitly generated magic necessary tosupport <code class="literal">try</code> and <code class="literal">catch</code> blocksand thrown objects. (Language supportfor <code class="literal">-fno-exceptions</code> is documented in the GNUGCC <a class="ulink" href="http://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#Code-Gen-Options" target="_top">manual</a>.)</p><p>Before detailing the library supportfor <code class="literal">-fno-exceptions</code>, first a passing note onthe things lost when this flag is used: it will break exceptionstrying to pass through code compiledwith <code class="literal">-fno-exceptions</code> whether or not that codehas any <code class="literal">try</code> or <code class="literal">catch</code>constructs. If you might have some code that throws, you shouldn'tuse <code class="literal">-fno-exceptions</code>. If you have some code thatuses <code class="literal">try</code> or <code class="literal">catch</code>, youshouldn't use <code class="literal">-fno-exceptions</code>.</p><p>And what it to be gained, tinkering in the back alleys with alanguage like this? Exception handling overhead can be measuredin the size of the executable binary, and varies with thecapabilities of the underlying operating system and specificconfiguration of the C++ compiler. On recent hardware with GNUsystem software of the same age, the combined code and data sizeoverhead for enabling exception handling is around 7%. Of course,if code size is of singular concern than using the appropriateoptimizer setting with exception handling enabled(ie, <code class="literal">-Os -fexceptions</code>) may save up to twicethat, and preserve error checking.</p><p>So. Hell bent, we race down the slippery track, knowing the brakesare a little soft and that the right front wheel has a tendency towobble at speed. Go on: detail the standard library supportfor <code class="literal">-fno-exceptions</code>.</p><p>In sum, valid C++ code with exception handling is transformed intoa dialect without exception handling. In detailed steps: all useof the C++keywords <code class="literal">try</code>, <code class="literal">catch</code>,and <code class="literal">throw</code> in the standard library have beenpermanently replaced with the pre-processor controlled equivalentsspelled <code class="literal">__try</code>, <code class="literal">__catch</code>,and <code class="literal">__throw_exception_again</code>. They are definedas follows.</p><pre class="programlisting">#ifdef __EXCEPTIONS# define __try try# define __catch(X) catch(X)# define __throw_exception_again throw#else# define __try if (true)# define __catch(X) if (false)# define __throw_exception_again#endif</pre><p>In addition, for every object derived fromclass <code class="classname">exception</code>, there exists a correspondingfunction with C language linkage. An example:</p><pre class="programlisting">#ifdef __EXCEPTIONSvoid __throw_bad_exception(void){ throw bad_exception(); }#elsevoid __throw_bad_exception(void){ abort(); }#endif</pre><p>The last language feature needing to be transformedby <code class="literal">-fno-exceptions</code> is treatment of exceptionspecifications on member functions. Fortunately, the compiler dealswith this by ignoring exception specifications and so no alternatesource markup is needed.</p><p>By using this combination of language re-specification by thecompiler, and the pre-processor tricks and the functionalindirection layer for thrown exception objects by the library,libstdc++ files can be compiledwith <code class="literal">-fno-exceptions</code>.</p><p>User code that uses C++ keywordslike <code class="literal">throw</code>, <code class="literal">try</code>,and <code class="literal">catch</code> will produce errors even if the usercode has included libstdc++ headers and is using constructslike <code class="classname">basic_iostream</code>. Even though the standardlibrary has been transformed, user code may need modification. Usercode that attempts or expects to do error checking on standardlibrary components compiled with exception handling disabled shouldbe evaluated and potentially made conditional.</p><p>Some issues remain with this approach (see bugzilla entry25191). Code paths are not equivalent, inparticular <code class="literal">catch</code> blocks are not evaluated. Alsoproblematic are <code class="literal">throw</code> expressions expecting auser-defined throw handler. Known problem areas in the standardlibrary include using an instanceof <code class="classname">basic_istream</code>with <code class="function">exceptions</code> set to specific<span class="type">ios_base::iostate</span> conditions, orcascading <code class="literal">catch</code> blocks that dispatch errorhandling or recovery efforts based on the type of exception objectthrown.</p><p>Oh, and by the way: none of this hackery is at allspecial. (Although perhaps well-deserving of a raised eyebrow.)Support continues to evolve and may change in the future. Similarand even additional techniques are used in other C++ libraries andcompilers.</p><p>C++ hackers with a bent for language and control-flow purity havebeen successfully consoled by grizzled C veterans lamenting thesubstitution of the C language keyword<code class="literal">const</code> with the uglifieddoppelganger <code class="literal">__const</code>.</p></div><div class="sect2" title="Compatibility"><div class="titlepage"><div><div><h3 class="title"><a id="intro.using.exception.compat"></a>Compatibility</h3></div></div></div><div class="sect3" title="With C"><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>C language code that is expecting to interoperate with C++ should becompiled with <code class="literal">-fexceptions</code>. This will makedebugging a C language function called as part of C++-induced stackunwinding possible.</p><p>In particular, unwinding into a frame with no exception handlingdata will cause a runtime abort. If the unwinder runs out of unwindinfo before it finds a handler, <code class="function">std::terminate()</code>is called.</p><p>Please note that most development environments should take care ofgetting these details right. For GNU systems, all appropriate partsof the GNU C library are already compiledwith <code class="literal">-fexceptions</code>.</p></div><div class="sect3" title="With POSIX thread cancellation"><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>GNU systems re-use some of the exception handling mechanisms totrack control flow for <code class="literal">POSIX</code> thread cancellation.</p><p>Cancellation points are functions defined by POSIX as worthy ofspecial treatment. The standard library may use some of thesefunctions to implement parts of the ISO C++ standard or depend onthem for extensions.</p><p>Of note:</p><p><code class="function">nanosleep</code>,<code class="function">read</code>, <code class="function">write</code>, <code class="function">open</code>, <code class="function">close</code>,and <code class="function">wait</code>.</p><p>The parts of libstdc++ that use C library functions marked ascancellation points should take pains to be exception neutral.Failing this, <code class="literal">catch</code> blocks have been augmented toshow that the POSIX cancellation object is in flight.</p><p>This augmentation adds a <code class="literal">catch</code> blockfor <code class="classname">__cxxabiv1::__forced_unwind</code>, which is theobject representing the POSIX cancellation object. Like so:</p><pre class="programlisting">catch(const __cxxabiv1::__forced_unwind&){this->_M_setstate(ios_base::badbit);throw;}catch(...){ this->_M_setstate(ios_base::badbit); }</pre></div></div><div class="bibliography" title="Bibliography"><div class="titlepage"><div><div><h3 class="title"><a id="using.exceptions.biblio"></a>Bibliography</h3></div></div></div><div class="biblioentry" title="System Interface Definitions, Issue 7 (IEEE Std. 1003.1-2008)"><a id="id612927"></a><p><span class="title"><i>System Interface Definitions, Issue 7 (IEEE Std. 1003.1-2008)</i>. </span><span class="pagenums">2.9.5 Thread Cancellation. </span><span class="copyright">Copyright Β© 2008The Open Group/The Institute of Electrical and Electronics Engineers, Inc.. </span><span class="biblioid"><a class="ulink" href="http://www.opengroup.org/austin/" target="_top"></a>. </span></p></div><div class="biblioentry" title="Error and Exception Handling"><a id="id692579"></a><p><span class="title"><i>Error and Exception Handling</i>. </span><span class="author"><span class="firstname">David</span> <span class="surname">Abrahams </span>. </span><span class="publisher"><span class="publishername">Boost. </span></span><span class="biblioid"><a class="ulink" href="http://www.boost.org/community/error_handling.html" target="_top"></a>. </span></p></div><div class="biblioentry" title="Exception-Safety in Generic Components"><a id="id622989"></a><p><span class="title"><i>Exception-Safety in Generic Components</i>. </span><span class="author"><span class="firstname">David</span> <span class="surname">Abrahams</span>. </span><span class="publisher"><span class="publishername">Boost. </span></span><span class="biblioid"><a class="ulink" href="http://www.boost.org/community/exception_safety.html" target="_top"></a>. </span></p></div><div class="biblioentry" title="Standard Library Exception Policy"><a id="id614001"></a><p><span class="title"><i>Standard Library Exception Policy</i>. </span><span class="author"><span class="firstname">Matt</span> <span class="surname">Austern</span>. </span><span class="publisher"><span class="publishername">WG21 N1077. </span></span><span class="biblioid"><a class="ulink" href="www.open-std.org/jtc1/sc22/wg21/docs/papers/1997/N1077.pdf" target="_top"></a>. </span></p></div><div class="biblioentry" title="ia64 c++ abi exception handling"><a id="id599408"></a><p><span class="title"><i>ia64 c++ abi exception handling</i>. </span><span class="author"><span class="firstname">Richard</span> <span class="surname">Henderson</span>. </span><span class="publisher"><span class="publishername">GNU. </span></span><span class="biblioid"><a class="ulink" href="http://gcc.gnu.org/ml/gcc-patches/2001-03/msg00661.html" target="_top"></a>. </span></p></div><div class="biblioentry" title="Appendix E: Standard-Library Exception Safety"><a id="id657794"></a><p><span class="title"><i>Appendix E: Standard-Library Exception Safety</i>. </span><span class="author"><span class="firstname">Bjarne</span> <span class="surname">Stroustrup</span>. </span><span class="biblioid"><a class="ulink" href="http://www.research.att.com/~bs/3rd_safe.pdf" target="_top"></a>. </span></p></div><div class="biblioentry" title="Exceptional C++"><a id="id635762"></a><p><span class="title"><i>Exceptional C++</i>. </span><span class="pagenums">Exception-Safety Issues and Techniques. </span><span class="author"><span class="firstname">Herb</span> <span class="surname">Sutter</span>. </span></p></div><div class="biblioentry" title="exception_defines.h #defines try/catch"><a id="id604495"></a><p><span class="title"><i>exception_defines.h #defines try/catch</i>. </span><span class="subtitle">GCC Bug <a class="ulink" href="http://gcc.gnu.org/PR25191" target="_top">25191</a>. </span><span class="biblioid">. </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="../spine.html">Home</a></td><td width="40%" align="right" valign="top">Β Debugging Support</td></tr></table></div></body></html>