-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathV2-C01.xml
More file actions
2630 lines (2085 loc) · 85.6 KB
/
V2-C01.xml
File metadata and controls
2630 lines (2085 loc) · 85.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-8"?>
<!-- -*- sgml -*- -->
<!--
Editor: Emacs 21/PSGML
Traducción original:
Formateado DocBook:
Texto original en:
http://arco.inf-cr.uclm.es/~david.villa/pensar_en_C++/TICv2/html/TicV2.html#_Toc53985615
=== AVISO ===
¡¡¡ No borres el texto original en inglés!!!
-->
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
"http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd">
<chapter
xmlns:xi="http://www.w3.org/2001/XInclude"
id="C01">
<!-- Exception Handling -->
<title>Tratamiento de excepciones</title>
<!--
Improving error recovery is one of the most powerful ways you can
increase the robustness of your code.
-->
<para>
Mejorar la recuperación de errores es una de las maneras más potentes
de incrementar la robustez de su código.
</para>
<!--
Unfortunately, it's almost accepted practice to ignore error conditions,
as if we're in a state of denial about errors. One reason, no doubt, is
the tediousness and code bloat of checking for many errors. For example,
printf( ) returns the number of characters that were successfully
printed, but virtually no one checks this value. The proliferation of
code alone would be disgusting, not to mention the difficulty it would
add in reading the code.
-->
<para>
</para>
<!--
The problem with C's approach to error handling could be thought of as
coupling-the user of a function must tie the error-handling code so
closely to that function that it becomes too ungainly and awkward to
use.
-->
<para>
</para>
<!--
One of the major features in C++ is exception handling, which is a
better way of thinking about and handling errors. With exception
handling:
-->
<para>
Una de las principales características de C++ es el tratamiento o
manejo de excepciones, el cual es una manera mejor de pensar acerca
de los errores y su tratamiento. Con el tratamiento de excepciones:
</para>
<!--
1. Error-handling code is not nearly so tedious to write, and it
doesn't become mixed up with your "normal" code. You write the code you
want to happen; later in a separate section you write the code to cope
with the problems. If you make multiple calls to a function, you handle
the errors from that function once, in one place.
-->
<para>
1. El código de manejo de errores no resulta tan tedioso de escribir
y no se entremezcla con su código «normal». Usted escribe el código
que desea que se ejecute, y más tarde, en una sección aparte, el código
que se encarga de los problemas. Si realiza varias llamadas a la misma
función, el manejo de errores de esa función se hará una sola vez, en un
solo lugar.
</para>
<!--
2. Errors cannot be ignored. If a function needs to send an error
message to the caller of that function, it "throws" an object
representing that error out of the function. If the caller doesn't
"catch" the error and handle it, it goes to the next enclosing dynamic
scope, and so on until the error is either caught or the program
terminates because there was no handler to catch that type of exception.
-->
<para>
2. Los errores no pueden ser ignorados. Si una función necesita enviar
un mensaje de error al invocador de esa función, ésta «lanza» un objeto
que representa a ese error fuera de la función. Si el invocador no
«captura» el error y lo trata, éste pasa al siguiente ámbito abarcador,
y así hasta que el error es capturado o el programa termina al no existir
un manejador adecuado para ese tipo de excepción.
</para>
<!--
This chapter examines C's approach to error handling (such as it is),
discusses why it did not work well for C, and explains why it won't work
at all for C++. This chapter also covers try, throw, and catch, the C++
keywords that support exception handling.
-->
<para>
</para>
<sect1>
<!-- Traditional error handling -->
<title>Tratamiento tradicional de errores</title>
<!--
In most of the examples in these volumes, we use assert( ) as it was
intended: for debugging during development with code that can be
disabled with #define NDEBUG for the shipping product. Runtime error
checking uses the require.h functions (assure( ) and require( ))
developed in Chapter 9 in Volume 1 and repeated here in Appendix
B. These functions are a convenient way to say, "There's a problem here
you'll probably want to handle with some more sophisticated code, but
you don't need to be distracted by it in this example." The require.h
functions might be enough for small programs, but for complicated
products you'll want to write more sophisticated error-handling code.
-->
<para>
En la mayoría de ejemplos de estos volúmenes, usamos la función assert()
para lo que fue concebida: para la depuración durante el desarrollo
insertando código que puede deshabilitarse con #define NDEBUG en un producto
comercial. Para la comprobación de errores en tiempo de ejecución
se utilizan las funciones de require.h (assure( ) y require( ))
desarrolladas en el capítulo 9 del Volumen 1 y repetidas aquí en el
Apéndice B. Estas funciones son un modo conveniente de decir, «Hay un
problema aquí que probablemente quiera manejar con un código algo
más sofisticado, pero no es necesario que se distraiga con eso en
este ejemplo.» Las funciones de require.h pueden parecer suficientes
para programas pequeños, pero para productos complicados deseará
escribir un código de manejo de errores más sofisticado.
</para>
<!--
Error handling is quite straightforward when you know exactly what to
do, because you have all the necessary information in that context. You
can just handle the error at that point.
-->
<para>
El tratamiento de errores es bastante sencillo cuando uno sabe
exactamente qué hacer, puesto que se tiene toda la información
necesaria en ese contexto. Simplemente se trata el error en ese punto.
</para>
<!--
The problem occurs when you don't have enough information in that
context, and you need to pass the error information into a different
context where that information does exist. In C, you can handle this
situation using three approaches:
-->
<para>
El problema ocurre cuando no se tiene suficiente información en ese
contexto, y se necesita pasar la información sobre el error a un
contexto diferente donde esa información sí que existe. En C, esta
situación puede tratarse usando tres enfoques:
</para>
<!--
1. Return error information from the function or, if the return value
cannot be used this way, set a global error condition flag. (Standard C
provides errno and perror( ) to support this.) As mentioned earlier, the
programmer is likely to ignore the error information because tedious and
obfuscating error checking must occur with each function call. In
addition, returning from a function that hits an exceptional condition
might not make sense.
-->
<para>
</para>
<!--
2. Use the little-known Standard C library signal-handling system,
implemented with the signal( ) function (to determine what happens when
the event occurs) and raise( ) (to generate an event). Again, this
approach involves high coupling because it requires the user of any
library that generates signals to understand and install the appropriate
signal-handling mechanism. In large projects the signal numbers from
different libraries might clash.
-->
<para>
2. Usar el poco conocido sistema de manejo de señales de la biblioteca
estándar de C, implementado en las funciones signal( ) (para determinar
lo que ocurre cuando se presenta un evento) y raise( ) (para generar un evento).
De nuevo, esta alternativa supone un alto acoplamiento debido a que
requiere que el usuario de cualquier biblioteca que genere señales
entienda e instale el mecanismo de manejo de señales adecuado. En proyectos
grandes los números de las señales de las diferentes bibliotecas puede llegar
a entrar en conflicto.
</para>
<!--
3. Use the nonlocal goto functions in the Standard C library: setjmp( )
and longjmp( ). With setjmp( ) you save a known good state in the
program, and if you get into trouble, longjmp( ) will restore that
state. Again, there is high coupling between the place where the state
is stored and the place where the error occurs.
-->
<para>
</para>
<!--
When considering error-handling schemes with C++, there's an additional
critical problem: The C techniques of signals and setjmp( )/longjmp( )
do not call destructors, so objects aren't properly cleaned up. (In
fact, if longjmp( ) jumps past the end of a scope where destructors
should be called, the behavior of the program is undefined.) This makes
it virtually impossible to effectively recover from an exceptional
condition because you'll always leave objects behind that haven't been
cleaned up and that can no longer be accessed. The following example
demonstrates this with setjmp/longjmp:
-->
<para>
Cuando se consideran los esquemas de tratamiento de errores para C++,
hay un problema adicional que es crítico: Las técnicas de C de señales
y setjmp( )/longjmp( ) no llaman a los destructores, por lo que los objetos
no se limpian adecuadamente. (De hecho, si longjmp( ) salta más allá
del final de un ámbito donde los destructores deben ser llamados, el
comportamiento del programa es indefinido.) Esto hace casi imposible
recuperarse efectivamente de una condición excepcional, puesto que
siempre se están dejando objetos detrás sin limpiar y a los que ya
no se tiene acceso. El siguiente ejemplo lo demuestra con setjmp/longjmp:
</para>
//: V2C01:Nonlocal.cpp
<!--
The setjmp() function is odd because if you call it directly, it stores
all the relevant information about the current processor state (such as
the contents of the instruction pointer and runtime stack pointer) in
the jmp_buf and returns zero. In this case it behaves like an ordinary
function. However, if you call longjmp( ) using the same jmp_buf, it's
as if you're returning from setjmp( ) again-you pop right out the back
end of the setjmp( ). This time, the value returned is the second
argument to longjmp( ), so you can detect that you're actually coming
back from a longjmp( ). You can imagine that with many different
jmp_bufs, you could pop around to many different places in the
program. The difference between a local goto (with a label) and this
nonlocal goto is that you can return to any pre-determined location
higher up in the runtime stack with setjmp( )/longjmp( ) (wherever
you've placed a call to setjmp( )).
-->
<para>
</para>
<!--
The problem in C++ is that longjmp( ) doesn't respect objects; in
particular it doesn't call destructors when it jumps out of a scope.[1]
Destructor calls are essential, so this approach won't work with C++. In
fact, the C++ Standard states that branching into a scope with goto
(effectively bypassing constructor calls), or branching out of a scope
with longjmp( ) where an object on the stack has a destructor,
constitutes undefined behavior.
-->
<para>
El problema con C++ es que longjmp( ) no respeta los objetos; en particular
no llama a los destructores cuando salta fuera de un ámbito.[1]
Puesto que las llamadas a los destructores son esenciales, esta
propuesta no es válida para C++. De hecho, el estándar de C++ aclara
que saltar a un ámbito con goto (pasando por alto las llamadas a los
constructores), o saltar fuera de un ámbito con longjmp( ) donde un
objeto en la pila posee un destructor, constituye un comportamiento
indefinido.
</para>
</sect1>
<sect1>
<!-- Throwing an exception -->
<title>Lanzar una excepción</title>
<!--
If you encounter an exceptional situation in your code-that is, if you
don't have enough information in the current context to decide what to
do-you can send information about the error into a larger context by
creating an object that contains that information and "throwing" it out
of your current context. This is called throwing an exception. Here's
what it looks like:
-->
<para>
Si usted se encuentra en su código con una situación excepcional-es decir,
si no tiene suficiente información en el contexto actual para decidir
lo que hacer- puede enviar información acerca del error a un contexto
mayor creando un objeto que contenga esa información y «lanzándolo»
fuera de su contexto actual. Esto es lo que se llama lanzar una
excepción. Este es el aspecto que tiene:
</para>
//: V2C01:MyError.cpp {RunByHandd}
<!--
MyError is an ordinary class, which in this case takes a char* as a
constructor argument. You can use any type when you throw (including
built-in types), but usually you'll create special classes for throwing
exceptions.
-->
<para>
MyError es una clase normal, que en este caso acepta un char*
como argumento del constructor. Usted puede usar cualquier tipo
para lanzar (incluyendo los tipos predefinidos), pero normalmente
creará clases especial para lanzar excepciones.
</para>
<!--
The keyword throw causes a number of relatively magical things to
happen. First, it creates a copy of the object you're throwing and, in
effect, "returns" it from the function containing the throw expression,
even though that object type isn't normally what the function is
designed to return. A naive way to think about exception handling is as
an alternate return mechanism (although you'll find you can get into
trouble if you take that analogy too far). You can also exit from
ordinary scopes by throwing an exception. In any case, a value is
returned, and the function or scope exits.
-->
<para>
La palabra clave throw hace que suceda una serie de cosas relativamente
mágicas. En primer lugar se crea una copia del objeto que se está
lanzando y se «devuelve» desde la función que contiene la
expresión throw, aun cuando ese tipo de objeto no es lo que normalmente
la función está diseñada para devolver. Un modo simplificado de pensar
acerca del tratamiento de excepciones es como un mecanismo alternativo
de retorno (aunque llegará a tener problemas si lleva esta analogía
demasiado lejos). También es posible salir de ámbitos normales lanzando
una excepción. En cualquier caso se devuelve un valor y se sale de la
función o ámbito.
</para>
<!--
Any similarity to a return statement ends there because where you return
is some place completely different from where a normal function call
returns. (You end up in an appropriate part of the code-called an
exception handler-that might be far removed from where the exception was
thrown.) In addition, any local objects created by the time the
exception occurs are destroyed. This automatic cleanup of local objects
is often called "stack unwinding."
-->
<para>
</para>
<!--
In addition, you can throw as many different types of objects as you
want. Typically, you'll throw a different type for each category of
error. The idea is to store the information in the object and in the
name of its class so that someone in a calling context can figure out
what to do with your exception.
-->
<para>
Además es posible lanzar tantos tipos de objetos diferentes como se
quiera. Típicamente, para cada categoría de error se lanzará un tipo
diferente. La idea es almacenar la información en el objeto y en el
nombre de la clase con el fin de quien esté en el contexto invocador
pueda averiguar lo que hacer con esa excepción.
</para>
</sect1>
<sect1>
<!-- Catching an exception -->
<title>Capturar una excepción</title>
<!--
As mentioned earlier, one of the advantages of C++ exception handling is
that you can concentrate on the problem you're trying to solve in one
place, and then deal with the errors from that code in another place.
-->
<para>
</para>
<sect2>
<!-- The try block -->
<title>El bloque <kw>try</kw></title>
<!--
If you're inside a function and you throw an exception (or a called
function throws an exception), the function exits because of the thrown
exception. If you don't want a throw to leave a function, you can set up
a special block within the function where you try to solve your actual
programming problem (and potentially generate exceptions). This block is
called the try block because you try your various function calls
there. The try block is an ordinary scope, preceded by the keyword try:
-->
<para>
</para>
<programlisting>
try {
// Code that may generate exceptions
}
</programlisting>
<!--
If you check for errors by carefully examining the return codes from the
functions you use, you need to surround every function call with setup
and test code, even if you call the same function several times. With
exception handling, you put everything in a try block and handle
exceptions after the try block. Thus, your code is a lot easier to write
and to read because the goal of the code is not confused with the error
handling.
-->
<para>
</para>
</sect2>
<sect2>
<!-- Exception handlers -->
<title>Manejadores de excepción</title>
<!--
Of course, the thrown exception must end up some place. This place is
the exception handler, and you need one exception handler for every
exception type you want to catch. However, polymorphism also works for
exceptions, so one exception handler can work with an exception type and
classes derived from that type.
-->
<para>
</para>
<!--
Exception handlers immediately follow the try block and are denoted by
the keyword catch:
-->
<para>
</para>
<programlisting>
try {
// Code that may generate exceptions
} catch(type1 id1) {
// Handle exceptions of type1
} catch(type2 id2) {
// Handle exceptions of type2
} catch(type3 id3)
// Etc...
} catch(typeN idN)
// Handle exceptions of typeN
}
// Normal execution resumes here...
</programlisting>
<!--
The syntax of a catch clause resembles functions that take a single
argument. The identifier (id1, id2, and so on) can be used inside the
handler, just like a function argument, although you can omit the
identifier if it's not needed in the handler. The exception type usually
gives you enough information to deal with it.
-->
<para>
</para>
<!--
The handlers must appear directly after the try block. If an exception
is thrown, the exception-handling mechanism goes hunting for the first
handler with an argument that matches the type of the exception. It then
enters that catch clause, and the exception is considered handled. (The
search for handlers stops once the catch clause is found.) Only the
matching catch clause executes; control then resumes after the last
handler associated with that try block.
-->
<para>
</para>
<!--
Notice that, within the try block, a number of different function calls
might generate the same type of exception, but you need only one
handler.
-->
<para>
</para>
<!--
To illustrate try and catch, the following variation of Nonlocal.cpp
replaces the call to setjmp( ) with a try block and replaces the call to
longjmp( ) with a throw statement:
-->
<para>
</para>
//: V2C01:Nonlocal2.cpp
<!--
When the throw statement in oz( ) executes, program control backtracks
until it finds the catch clause that takes an int parameter. Execution
resumes with the body of that catch clause. The most important
difference between this program and Nonlocal.cpp is that the destructor
for the object rb is called when the throw statement causes execution to
leave the function oz( ).
-->
<para>
</para>
</sect2>
<sect2>
<!-- Termination and resumption -->
<title></title>
<!--
There are two basic models in exception-handling theory: termination and
resumption. In termination (which is what C++ supports), you assume the
error is so critical that there's no way to automatically resume
execution at the point where the exception occurred. In other words,
whoever threw the exception decided there was no way to salvage the
situation, and they don't want to come back.
-->
<para>
</para>
<!--
The alternative error-handling model is called resumption, first
introduced with the PL/I language in the 1960s.[2] Using resumption
semantics means that the exception handler is expected to do something
to rectify the situation, and then the faulting code is automatically
retried, presuming success the second time. If you want resumption in
C++, you must explicitly transfer execution back to the code where the
error occurred, usually by repeating the function call that sent you
there in the first place. It is not unusual to place your try block
inside a while loop that keeps reentering the try block until the result
is satisfactory.
-->
<para>
</para>
<!--
Historically, programmers using operating systems that supported
resumptive exception handling eventually ended up using termination-like
code and skipping resumption. Although resumption sounds attractive at
first, it seems it isn't quite so useful in practice. One reason may be
the distance that can occur between the exception and its handler. It is
one thing to terminate to a handler that's far away, but to jump to that
handler and then back again may be too conceptually difficult for large
systems where the exception is generated from many points.
-->
<para>
</para>
</sect2>
</sect1>
<sect1>
<!-- Exception matching -->
<title></title>
<!--
When an exception is thrown, the exception-handling system looks through
the "nearest" handlers in the order they appear in the source code. When
it finds a match, the exception is considered handled and no further
searching occurs.
-->
<para>
</para>
<!--
Matching an exception doesn't require a perfect correlation between the
exception and its handler. An object or reference to a derived-class
object will match a handler for the base class. (However, if the handler
is for an object rather than a reference, the exception object is
"sliced"-truncated to the base type-as it is passed to the handler. This
does no damage, but loses all the derived-type information.) For this
reason, as well as to avoid making yet another copy of the exception
object, it is always better to catch an exception by reference instead
of by value.[3] If a pointer is thrown, the usual standard pointer
conversions are used to match the exception. However, no automatic type
conversions are used to convert from one exception type to another in
the process of matching. For example:
-->
<para>
</para>
//: V2C01:Autoexcp.cpp
<!--
Even though you might think the first handler could be matched by
converting an Except1 object into an Except2 using the converting
constructor, the system will not perform such a conversion during
exception handling, and you'll end up at the Except1 handler.
-->
<para>
</para>
<!--
The following example shows how a base-class handler can catch a
derived-class exception:
-->
<para>
</para>
//: V2C01:Basexcpt.cpp
<!--
Here, the exception-handling mechanism will always match a Trouble
object, or anything that is a Trouble (through public inheritance),[4]
to the first handler. That means the second and third handlers are never
called because the first one captures them all. It makes more sense to
catch the derived types first and put the base type at the end to catch
anything less specific.
-->
<para>
</para>
<!--
Notice that these examples catch exceptions by reference, although for
these classes it isn't important because there are no additional members
in the derived classes, and there are no argument identifiers in the
handlers anyway. You'll usually want to use reference arguments rather
than value arguments in your handlers to avoid slicing off information.
-->
<para>
</para>
<sect2>
<!-- Catching any exception -->
<title>Capturar cualquier excepción</title>
<!--
Sometimes you want to create a handler that catches any type of
exception. You do this using the ellipsis in the argument list:
-->
<para>
</para>
<programlisting>
catch(...) {
cout << "an exception was thrown" << endl;
}
</programlisting>
<!--
Because an ellipsis catches any exception, you'll want to put it at the
end of your list of handlers to avoid pre-empting any that follow it.
-->
<para>
</para>
<!--
The ellipsis gives you no possibility to have an argument, so you can't
know anything about the exception or its type. It's a "catchall." Such a
catch clause is often used to clean up some resources and then rethrow
the exception.
-->
<para>
</para>
</sect2>
<sect2>
<!-- Rethrowing an exception -->
<title>Relanzar una excepción</title>
<!--
You usually want to rethrow an exception when you have some resource
that needs to be released, such as a network connection or heap memory
that needs to be deallocated. (See the section "Resource Management"
later in this chapter for more detail). If an exception occurs, you
don't necessarily care what error caused the exception-you just want to
close the connection you opened previously. After that, you'll want to
let some other context closer to the user (that is, higher up in the
call chain) handle the exception. In this case the ellipsis
specification is just what you want. You want to catch any exception,
clean up your resource, and then rethrow the exception for handling
elsewhere. You rethrow an exception by using throw with no argument
inside a handler:
-->
<para>
</para>
<programlisting>
catch(...) {
cout << "an exception was thrown" << endl;
// Deallocate your resource here, and then rethrow
throw;
}
</programlisting>
<!--
Any further catch clauses for the same try block are still ignored-the
throw causes the exception to go to the exception handlers in the
next-higher context. In addition, everything about the exception object
is preserved, so the handler at the higher context that catches the
specific exception type can extract any information the object may
contain.
-->
<para>
</para>
</sect2>
<sect2>
<!-- Uncaught exceptions -->
<title>Excepciones no capturadas</title>
<!--
As we explained in the beginning of this chapter, exception handling is
considered better than the traditional return-an-error-code technique
because exceptions can't be ignored, and because the error handling
logic is separated from the problem at hand. If none of the exception
handlers following a particular try block matches an exception, that
exception moves to the next-higher context, that is, the function or try
block surrounding the try block that did not catch the exception. (The
location of this try block is not always obvious at first glance, since
it's higher up in the call chain.) This process continues until, at some
level, a handler matches the exception. At that point, the exception is
considered "caught," and no further searching occurs. The terminate( )
function
-->
<para>
</para>
<!--
If no handler at any level catches the exception, the special library
function terminate( ) (declared in the <exception> header) is
automatically called. By default, terminate( ) calls the Standard C
library function abort( ) , which abruptly exits the program. On Unix
systems, abort( ) also causes a core dump. When abort( ) is called, no
calls to normal program termination functions occur, which means that
destructors for global and static objects do not execute. The terminate(
) function also executes if a destructor for a local object throws an
exception while the stack is unwinding (interrupting the exception that
was in progress) or if a global or static object's constructor or
destructor throws an exception. (In general, do not allow a destructor
to throw an exception.) The set_terminate( ) function
-->
<para>
</para>
<!--
You can install your own terminate( ) function using the standard
set_terminate( ) function, which returns a pointer to the terminate( )
function you are replacing (which will be the default library version
the first time you call it), so you can restore it later if you
want. Your custom terminate( ) must take no arguments and have a void
return value. In addition, any terminate( ) handler you install must not
return or throw an exception, but instead must execute some sort of
program-termination logic. If terminate( ) is called, the problem is
unrecoverable.
-->
<para>
</para>
<!--
The following example shows the use of set_terminate( ). Here, the
return value is saved and restored so that the terminate( ) function can
be used to help isolate the section of code where the uncaught exception
occurs:
-->
<para>
</para>
//: V2C01:Terminator.cpp
<!--
The definition of old_terminate looks a bit confusing at first: it not
only creates a pointer to a function, but it initializes that pointer to
the return value of set_terminate( ). Even though you might be familiar
with seeing a semicolon right after a pointer-to-function declaration,
here it's just another kind of variable and can be initialized when it
is defined.
-->
<para>
</para>
<!--
The class Botch not only throws an exception inside f( ), but also in
its destructor. This causes a call to terminate( ), as you can see in
main( ). Even though the exception handler says catch(...), which would
seem to catch everything and leave no cause for terminate( ) to be
called, terminate( ) is called anyway. In the process of cleaning up the
objects on the stack to handle one exception, the Botch destructor is
called, and that generates a second exception, forcing a call to
terminate( ). Thus, a destructor that throws an exception or causes one
to be thrown is usually a sign of poor design or sloppy coding.
-->
<para>
</para>
</sect2>
</sect1>
<sect1>
<!-- Cleaning up -->
<title>Limpieza</title>
<!--
Part of the magic of exception handling is that you can pop from normal
program flow into the appropriate exception handler. Doing so wouldn't
be useful, however, if things weren't cleaned up properly as the
exception was thrown. C++ exception handling guarantees that as you
leave a scope, all objects in that scope whose constructors have been
completed will have their destructors called.
-->
<para>
</para>
<!--
Here's an example that demonstrates that constructors that aren't
completed don't have the associated destructors called. It also shows
what happens when an exception is thrown in the middle of the creation
of an array of objects:
-->
<para>
</para>
//: V2C01:Cleanup.cpp
<!--
The class Trace keeps track of objects so that you can trace program
progress. It keeps a count of the number of objects created with a
static data member counter and tracks the number of the particular
object with objid.
-->
<para>
</para>
<!--
The main program creates a single object, n1 (objid 0), and then
attempts to create an array of five Trace objects, but an exception is
thrown before the fourth object (#3) is fully created. The object n2 is
never created. You can see the results in the output of the program:
-->
<para>
</para>
<screen>
constructing Trace #0
constructing Trace #1
constructing Trace #2
constructing Trace #3
destructing Trace #2
destructing Trace #1
destructing Trace #0
caught 3
</screen>
<!--
Three array elements are successfully created, but in the middle of the
constructor for the fourth element, an exception is thrown. Because the
fourth construction in main( ) (for array[2]) never completes, only the
destructors for objects array[1] and array[0] are called. Finally,
object n1 is destroyed, but not object n2, because it was never created.
-->
<para>
</para>
<sect2>
<!-- Resource management -->
<title>Gestión de recursos</title>
<!--
When writing code with exceptions, it's particularly important that you
always ask, "If an exception occurs, will my resources be properly
cleaned up?" Most of the time you're fairly safe, but in constructors
there's a particular problem: if an exception is thrown before a
constructor is completed, the associated destructor will not be called
for that object. Thus, you must be especially diligent while writing
your constructor.
-->
<para>
</para>
<!--
The difficulty is in allocating resources in constructors. If an
exception occurs in the constructor, the destructor doesn't get a chance
to deallocate the resource. This problem occurs most often with "naked"
pointers. For example:
-->
<para>
</para>
//: V2C01:Rawp.cpp
<!--
The output is
-->
<para>
</para>
<screen>
UseResources()
Cat()
Cat()
Cat()
allocating a Dog
inside handler
</screen>
<!--
The UseResources constructor is entered, and the Cat constructor is
successfully completed for the three array objects. However, inside
Dog::operator new( ), an exception is thrown (to simulate an
out-of-memory error). Suddenly, you end up inside the handler, without
the UseResources destructor being called. This is correct because the
UseResources constructor was unable to finish, but it also means the Cat
objects that were successfully created on the heap were never destroyed.
-->
<para>
</para>
</sect2>
<sect2>
<!-- Making everything an object -->
<title></title>
<!--
To prevent such resource leaks, you must guard against these "raw"
resource allocations in one of two ways:
-->
<para>
</para>
<!--
· You can catch exceptions inside the constructor and then release the
resource.
-->
<para>
</para>
<!--
· You can place the allocations inside an object's constructor, and you
can place the deallocations inside an object's destructor.
-->
<para>
</para>
<!--
Using the latter approach, each allocation becomes atomic, by virtue of
being part of the lifetime of a local object, and if it fails, the other
resource allocation objects are properly cleaned up during stack
unwinding. This technique is called Resource Acquisition Is