Account for prologue spills in reg_pressure scheduling
[official-gcc.git] / libstdc++-v3 / doc / html / manual / using_exceptions.html
blob83e4ba6eec94010fd5ef5c54d6deb476bcbe873e
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-NS Stylesheets V1.78.1" /><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="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="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.no"></a>Doing without</h3></div></div></div><p>
104 C++ is a language that strives to be as efficient as is possible
105 in delivering features. As such, considerable care is used by both
106 language implementer and designers to make sure unused features
107 not impose hidden or unexpected costs. The GNU system tries to be
108 as flexible and as configurable as possible. So, it should come as
109 no surprise that GNU C++ provides an optional language extension,
110 spelled <code class="literal">-fno-exceptions</code>, as a way to excise the
111 implicitly generated magic necessary to
112 support <code class="literal">try</code> and <code class="literal">catch</code> blocks
113 and thrown objects. (Language support
114 for <code class="literal">-fno-exceptions</code> is documented in the GNU
115 GCC <a class="link" href="http://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#Code-Gen-Options" target="_top">manual</a>.)
116 </p><p>Before detailing the library support
117 for <code class="literal">-fno-exceptions</code>, first a passing note on
118 the things lost when this flag is used: it will break exceptions
119 trying to pass through code compiled
120 with <code class="literal">-fno-exceptions</code> whether or not that code
121 has any <code class="literal">try</code> or <code class="literal">catch</code>
122 constructs. If you might have some code that throws, you shouldn't
123 use <code class="literal">-fno-exceptions</code>. If you have some code that
124 uses <code class="literal">try</code> or <code class="literal">catch</code>, you
125 shouldn't use <code class="literal">-fno-exceptions</code>.
126 </p><p>
127 And what it to be gained, tinkering in the back alleys with a
128 language like this? Exception handling overhead can be measured
129 in the size of the executable binary, and varies with the
130 capabilities of the underlying operating system and specific
131 configuration of the C++ compiler. On recent hardware with GNU
132 system software of the same age, the combined code and data size
133 overhead for enabling exception handling is around 7%. Of course,
134 if code size is of singular concern than using the appropriate
135 optimizer setting with exception handling enabled
136 (ie, <code class="literal">-Os -fexceptions</code>) may save up to twice
137 that, and preserve error checking.
138 </p><p>
139 So. Hell bent, we race down the slippery track, knowing the brakes
140 are a little soft and that the right front wheel has a tendency to
141 wobble at speed. Go on: detail the standard library support
142 for <code class="literal">-fno-exceptions</code>.
143 </p><p>
144 In sum, valid C++ code with exception handling is transformed into
145 a dialect without exception handling. In detailed steps: all use
146 of the C++
147 keywords <code class="literal">try</code>, <code class="literal">catch</code>,
148 and <code class="literal">throw</code> in the standard library have been
149 permanently replaced with the pre-processor controlled equivalents
150 spelled <code class="literal">__try</code>, <code class="literal">__catch</code>,
151 and <code class="literal">__throw_exception_again</code>. They are defined
152 as follows.
153 </p><pre class="programlisting">
154 #ifdef __EXCEPTIONS
155 # define __try try
156 # define __catch(X) catch(X)
157 # define __throw_exception_again throw
158 #else
159 # define __try if (true)
160 # define __catch(X) if (false)
161 # define __throw_exception_again
162 #endif
163 </pre><p>
164 In addition, for every object derived from
165 class <code class="classname">exception</code>, there exists a corresponding
166 function with C language linkage. An example:
167 </p><pre class="programlisting">
168 #ifdef __EXCEPTIONS
169 void __throw_bad_exception(void)
170 { throw bad_exception(); }
171 #else
172 void __throw_bad_exception(void)
173 { abort(); }
174 #endif
175 </pre><p>
176 The last language feature needing to be transformed
177 by <code class="literal">-fno-exceptions</code> is treatment of exception
178 specifications on member functions. Fortunately, the compiler deals
179 with this by ignoring exception specifications and so no alternate
180 source markup is needed.
181 </p><p>
182 By using this combination of language re-specification by the
183 compiler, and the pre-processor tricks and the functional
184 indirection layer for thrown exception objects by the library,
185 libstdc++ files can be compiled
186 with <code class="literal">-fno-exceptions</code>.
187 </p><p>
188 User code that uses C++ keywords
189 like <code class="literal">throw</code>, <code class="literal">try</code>,
190 and <code class="literal">catch</code> will produce errors even if the user
191 code has included libstdc++ headers and is using constructs
192 like <code class="classname">basic_iostream</code>. Even though the standard
193 library has been transformed, user code may need modification. User
194 code that attempts or expects to do error checking on standard
195 library components compiled with exception handling disabled should
196 be evaluated and potentially made conditional.
197 </p><p>
198 Some issues remain with this approach (see bugzilla entry
199 25191). Code paths are not equivalent, in
200 particular <code class="literal">catch</code> blocks are not evaluated. Also
201 problematic are <code class="literal">throw</code> expressions expecting a
202 user-defined throw handler. Known problem areas in the standard
203 library include using an instance
204 of <code class="classname">basic_istream</code>
205 with <code class="function">exceptions</code> set to specific
206 <span class="type">ios_base::iostate</span> conditions, or
207 cascading <code class="literal">catch</code> blocks that dispatch error
208 handling or recovery efforts based on the type of exception object
209 thrown.
210 </p><p>
211 Oh, and by the way: none of this hackery is at all
212 special. (Although perhaps well-deserving of a raised eyebrow.)
213 Support continues to evolve and may change in the future. Similar
214 and even additional techniques are used in other C++ libraries and
215 compilers.
216 </p><p>
217 C++ hackers with a bent for language and control-flow purity have
218 been successfully consoled by grizzled C veterans lamenting the
219 substitution of the C language keyword
220 <code class="literal">const</code> with the uglified
221 doppelganger <code class="literal">__const</code>.
222 </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>
223 C language code that is expecting to interoperate with C++ should be
224 compiled with <code class="literal">-fexceptions</code>. This will make
225 debugging a C language function called as part of C++-induced stack
226 unwinding possible.
227 </p><p>
228 In particular, unwinding into a frame with no exception handling
229 data will cause a runtime abort. If the unwinder runs out of unwind
230 info before it finds a handler, <code class="function">std::terminate()</code>
231 is called.
232 </p><p>
233 Please note that most development environments should take care of
234 getting these details right. For GNU systems, all appropriate parts
235 of the GNU C library are already compiled
236 with <code class="literal">-fexceptions</code>.
237 </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>
238 GNU systems re-use some of the exception handling mechanisms to
239 track control flow for <code class="literal">POSIX</code> thread cancellation.
240 </p><p>
241 Cancellation points are functions defined by POSIX as worthy of
242 special treatment. The standard library may use some of these
243 functions to implement parts of the ISO C++ standard or depend on
244 them for extensions.
245 </p><p>
246 Of note:
247 </p><p>
248 <code class="function">nanosleep</code>,
249 <code class="function">read</code>, <code class="function">write</code>, <code class="function">open</code>, <code class="function">close</code>,
250 and <code class="function">wait</code>.
251 </p><p>
252 The parts of libstdc++ that use C library functions marked as
253 cancellation points should take pains to be exception neutral.
254 Failing this, <code class="literal">catch</code> blocks have been augmented to
255 show that the POSIX cancellation object is in flight.
256 </p><p>
257 This augmentation adds a <code class="literal">catch</code> block
258 for <code class="classname">__cxxabiv1::__forced_unwind</code>, which is the
259 object representing the POSIX cancellation object. Like so:
260 </p><pre class="programlisting">
261 catch(const __cxxabiv1::__forced_unwind&amp;)
263 this-&gt;_M_setstate(ios_base::badbit);
264 throw;
266 catch(...)
267 { this-&gt;_M_setstate(ios_base::badbit); }
268 </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.8.9.2"></a><p><span class="title"><em>
269 <a class="link" href="http://www.opengroup.org/austin/" target="_top">
270 System Interface Definitions, Issue 7 (IEEE Std. 1003.1-2008)
271 </a>
272 </em>. </span><span class="pagenums">
273 2.9.5 Thread Cancellation
274 . </span><span class="copyright">Copyright © 2008
275 The Open Group/The Institute of Electrical and Electronics
276 Engineers, Inc.
277 . </span></p></div><div class="biblioentry"><a id="id-1.3.3.4.8.9.3"></a><p><span class="title"><em>
278 <a class="link" href="http://www.boost.org/community/error_handling.html" target="_top">
279 Error and Exception Handling
280 </a>
281 </em>. </span><span class="author"><span class="firstname">David</span> <span class="surname">Abrahams </span>. </span><span class="publisher"><span class="publishername">
282 Boost
283 . </span></span></p></div><div class="biblioentry"><a id="id-1.3.3.4.8.9.4"></a><p><span class="title"><em>
284 <a class="link" href="http://www.boost.org/community/exception_safety.html" target="_top">
285 Exception-Safety in Generic Components
286 </a>
287 </em>. </span><span class="author"><span class="firstname">David</span> <span class="surname">Abrahams</span>. </span><span class="publisher"><span class="publishername">
288 Boost
289 . </span></span></p></div><div class="biblioentry"><a id="id-1.3.3.4.8.9.5"></a><p><span class="title"><em>
290 <a class="link" href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1997/N1077.pdf" target="_top">
291 Standard Library Exception Policy
292 </a>
293 </em>. </span><span class="author"><span class="firstname">Matt</span> <span class="surname">Austern</span>. </span><span class="publisher"><span class="publishername">
294 WG21 N1077
295 . </span></span></p></div><div class="biblioentry"><a id="id-1.3.3.4.8.9.6"></a><p><span class="title"><em>
296 <a class="link" href="http://gcc.gnu.org/ml/gcc-patches/2001-03/msg00661.html" target="_top">
297 ia64 c++ abi exception handling
298 </a>
299 </em>. </span><span class="author"><span class="firstname">Richard</span> <span class="surname">Henderson</span>. </span><span class="publisher"><span class="publishername">
301 . </span></span></p></div><div class="biblioentry"><a id="id-1.3.3.4.8.9.7"></a><p><span class="title"><em>
302 <a class="link" href="http://www.research.att.com/~bs/3rd_safe.pdf" target="_top">
303 Appendix E: Standard-Library Exception Safety
304 </a>
305 </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.8.9.8"></a><p><span class="citetitle"><em class="citetitle">
306 Exceptional C++
307 </em>. </span><span class="pagenums">
308 Exception-Safety Issues and Techniques
309 . </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.8.9.9"></a><p><span class="title"><em>
310 <a class="link" href="http://gcc.gnu.org/PR25191" target="_top">
311 GCC Bug 25191: exception_defines.h #defines try/catch
312 </a>
313 </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>