Source

PensarEnC++ / V2-C01.xml

The branch 'PensarEnC++' does not exist.
Full commit
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
<?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 &lt;&lt; "an exception was thrown" &lt;&lt; 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 &lt;&lt; "an exception was thrown" &lt;&lt; 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
      Initialization (RAII for short) because it equates resource control with
      object lifetime. Using templates is an excellent way to modify the
      previous example to achieve this:
      -->
      <para>

      </para>


//: V2C01:Wrapped.cpp


      <!--
      The difference is the use of the template to wrap the pointers and make
      them into objects. The constructors for these objects are called before
      the body of the UseResources constructor, and any of these constructors
      that complete before an exception is thrown will have their associated
      destructors called during stack unwinding.
      -->
      <para>

      </para>

      <!--
      The PWrap template shows a more typical use of exceptions than you've
      seen so far: A nested class called RangeError is created to use in
      operator[ ] if its argument is out of range. Because operator[ ] returns
      a reference, it cannot return zero. (There are no null references.) This
      is a true exceptional condition-you don't know what to do in the current
      context and you can't return an improbable value. In this example,
      RangeError[5] is simple and assumes all the necessary information is in
      the class name, but you might also want to add a member that contains
      the value of the index, if that is useful.
      -->
      <para>

      </para>

      <!--
      Now the output is
      -->

      <para>

      </para>

<screen>
Cat()
Cat()
Cat()
PWrap constructor
allocating a Dog
~Cat()
~Cat()
~Cat()
PWrap destructor
inside handler
</screen>


      <!--
      Again, the storage allocation for Dog throws an exception, but this time
      the array of Cat objects is properly cleaned up, so there is no memory
      leak.
      -->
      <para>

      </para>

    </sect2>
    <sect2>
      <!-- auto_ptr -->
      <title><kw>auto_ptr</kw></title>

      <!--
      Since dynamic memory is the most frequent resource used in a typical C++
      program, the standard provides an RAII wrapper for pointers to heap
      memory that automatically frees the memory. The auto_ptr class template,
      defined in the <memory> header, has a constructor that takes a pointer
      to its generic type (whatever you use in your code). The auto_ptr class
      template also overloads the pointer operators * and -> to forward these
      operations to the original pointer the auto_ptr object is holding. So
      you can use the auto_ptr object as if it were a raw pointer. Here's how
      it works:
      -->
      <para>

      </para>


//: V2C01:Auto_ptr.cpp


      <!--
      The TraceHeap class overloads the operator new and operator delete so
      you can see exactly what's happening. Notice that, like any other class
      template, you specify the type you're going to use in a template
      parameter. You don't say TraceHeap*, however-auto_ptr already knows that
      it will be storing a pointer to your type. The second line of main( )
      verifies that auto_ptr's operator->( ) function applies the indirection
      to the original, underlying pointer. Most important, even though we
      didn't explicitly delete the original pointer, pMyObject's destructor
      deletes the original pointer during stack unwinding, as the following
      output verifies: Allocating TraceHeap object on the heap at address
      8930040 5 Deleting TraceHeap object at address 8930040
      -->
      <para>

      </para>

      <!--
      The auto_ptr class template is also handy for pointer data
      members. Since class objects contained by value are always destructed,
      auto_ptr members always delete the raw pointer they wrap when the
      containing object is destructed.[6]
      -->
      <para>

      </para>

    </sect2>
    <sect2>
      <!-- Function-level try blocks -->
      <title>Bloques <kw>try</kw> a nivel de función</title>

      <!--
      Since constructors can routinely throw exceptions, you might want to
      handle exceptions that occur when an object's member or base subobjects
      are initialized. To do this, you can place the initialization of such
      subobjects in a function-level try block. In a departure from the usual
      syntax, the try block for constructor initializers is the constructor
      body, and the associated catch block follows the body of the
      constructor, as in the following example:
      -->
      <para>

      </para>


//: V2C01:InitExcept.cpp {-bor}


      <!--
      Notice that the initializer list in the constructor for Derived goes
      after the try keyword but before the constructor body. If an exception
      does occur, the contained object is not constructed, so it makes no
      sense to return to the code that created it. For this reason, the only
      sensible thing to do is to throw an exception in the function-level
      catch clause.
      -->
      <para>

      </para>

      <!--
      Although it is not terribly useful, C++ also allows function-level try
      blocks for any function, as the following example illustrates:
      -->
      <para>

      </para>


//: V2C01:FunctionTryBlock.cpp {-bor}


      <!--
      In this case, the catch block can return in the same manner that the
      function body normally returns. Using this type of function-level try
      block isn't much different from inserting a try-catch around the code
      inside of the function body.
      -->
      <para>

      </para>

    </sect2>
  </sect1>
  <sect1>
    <!-- Standard exceptions -->
    <title>Excepciones estándar</title>

    <!--
    The exceptions used with the Standard C++ library are also available for
    your use. Generally it's easier and faster to start with a standard
    exception class than to try to define your own. If the standard class
    doesn't do exactly what you need, you can derive from it.
    -->
    <para>

    </para>

    <!--
    All standard exception classes derive ultimately from the class
    exception, defined in the header <exception>. The two main derived
    classes are logic_error and runtime_error, which are found in
    represents errors in programming logic, such as passing an invalid
    argument. Runtime errors are those that occur as the result of
    unforeseen forces such as hardware failure or memory exhaustion. Both
    runtime_error and logic_error provide a constructor that takes a
    std::string argument so that you can store a message in the exception
    object and extract it later with exception::what( ) , as the following
    program illustrates:
    -->
    <para>

    </para>


//: V2C01:StdExcept.cpp


    <!--
    Although the runtime_error constructor inserts the message into its
    std::exception subobject, std::exception does not provide a constructor
    that takes a std::string argument. You'll usually want to derive your
    exception classes from either runtime_error or logic_error (or one of
    their derivatives), and not from std::exception.
    -->
    <para>

    </para>

    <!-- The following tables describe the standard exception classes: -->
    <para>

    </para>

    <!-- exception

    The base class for all the exceptions thrown by the C++ Standard
    library. You can ask what( ) and retrieve the optional string with which
    the exception was initialized.
    -->
    <para>

    </para>

    <!-- logic_error

    Derived from exception. Reports program logic errors, which could
    presumably be detected by inspection.
    -->
    <para>

    </para>

    <!-- runtime_error

    Derived from exception. Reports runtime errors, which can presumably be
    detected only when the program executes.
    -->
    <para>

    </para>

    <!--
    The iostream exception class ios::failure is also derived from
    exception, but it has no further subclasses.
    -->
    <para>

    </para>

    <!--
    You can use the classes in both of the following tables as they are, or
    you can use them as base classes from which to derive your own more
    specific types of exceptions.
    -->
    <para>

    </para>

    <!-- Exception classes derived from logic_error -->
    <para>

    </para>

    <!-- domain_error

    Reports violations of a precondition. -->
    <para>

    </para>

    <!-- invalid_argument

    Indicates an invalid argument to the function from which it is thrown. -->
    <para>

    </para>

    <!-- length_error

    Indicates an attempt to produce an object whose length is greater than
    or equal to npos (the largest representable value of context's size
    type, usually std::size_t).
    -->
    <para>

    </para>

    <!-- out_of_range

    Reports an out-of-range argument. -->
    <para>

    </para>

    <!-- bad_cast

    Thrown for executing an invalid dynamic_cast expression in runtime type
    identification (see Chapter 8).
    -->
    <para>

    </para>

    <!-- bad_typeid

    Reports a null pointer p in an expression typeid(*p). (Again, a runtime
    type identification feature in Chapter 8).
    -->
    <para>

    </para>

    <!-- Exception classes derived from runtime_error -->
    <para>

    </para>

    <!-- range_error

    Reports violation of a postcondition. -->
    <para>

    </para>

    <!-- overflow_error

    Reports an arithmetic overflow. -->
    <para>

    </para>

    <!-- bad_alloc

    Reports a failure to allocate storage. -->
    <para>

    </para>

  </sect1>
  <sect1>
    <!-- Exception specifications -->
    <title>Especificaciones de excepciones</title>

    <!--
    You're not required to inform the people using your function what
    exceptions you might throw. However, failure to do so can be considered
    uncivilized because it means that users cannot be sure what code to
    write to catch all potential exceptions. If they have your source code,
    they can hunt through and look for throw statements, but often a library
    doesn't come with sources. Good documentation can help alleviate this
    problem, but how many software projects are well documented? C++
    provides syntax to tell the user the exceptions that are thrown by this
    function, so the user can handle them. This is the optional exception
    specification, which adorns a function's declaration, appearing after
    the argument list.
    -->
    <para>

    </para>

    <!--
    The exception specification reuses the keyword throw, followed by a
    parenthesized list of all the types of potential exceptions that the
    function can throw. Your function declaration might look like this:
    -->


<programlisting>
void f() throw(toobig, toosmall, divzero);
</programlisting>


    <!--
    As far as exceptions are concerned, the traditional function declaration
    -->


<programlisting>
void f();
</programlisting>


    <!--
    means that any type of exception can be thrown from the function. If you say
    -->


<programlisting>
void f() throw();
</programlisting>


    <!--
    no exceptions whatsoever will be thrown from the function (so you'd
    better be sure that no functions farther down in the call chain let any
    exceptions propagate up!).
    -->
    <para>

    </para>

    <!--
    For good coding policy, good documentation, and ease-of-use for the
    function caller, consider using exception specifications when you write
    functions that throw exceptions. (Variations on this guideline are
    discussed later in this chapter.)  The unexpected( ) function
    -->
    <para>

    </para>

    <!--
    If your exception specification claims you're going to throw a certain
    set of exceptions and then you throw something that isn't in that set,
    what's the penalty? The special function unexpected( ) is called when
    you throw something other than what appears in the exception
    specification. Should this unfortunate situation occur, the default
    unexpected( ) calls the terminate( ) function described earlier in this
    chapter.  The set_unexpected( ) function
    -->
    <para>

    </para>

    <!--
    Like terminate(), the unexpected() mechanism installs your own
    function to respond to unexpected exceptions. You do so with a function
    called set_unexpected( ), which, like set_terminate( ), takes the
    address of a function with no arguments and void return value. Also,
    because it returns the previous value of the unexpected( ) pointer, you
    can save it and restore it later. To use set_unexpected( ), include the
    header file <exception>. Here's an example that shows a simple use of
    the features discussed so far in this section:
    -->
    <para>

    </para>


//: V2C01:Unexpected.cpp


    <!--
    The classes Up and Fit are created solely to throw as exceptions. Often
    exception classes will be small, but they can certainly hold additional
    information so that the handlers can query for it.
    -->
    <para>

    </para>

    <!--
    The f( ) function promises in its exception specification to throw only
    exceptions of type Up and Fit, and from looking at the function
    definition, this seems plausible. Version one of g( ), called by f( ),
    doesn't throw any exceptions, so this is true. But if someone changes g(
    ) so that it throws a different type of exception (like the second
    version in this example, which throws an int), the exception
    specification for f( ) is violated.
    -->
    <para>

    </para>

    <!--
    The my_unexpected( ) function has no arguments or return value,
    following the proper form for a custom unexpected( ) function. It simply
    displays a message so that you can see that it was called, and then
    exits the program (exit(0) is used here so that the book's make process
    is not aborted). Your new unexpected( ) function should not have a
    return statement.
    -->
    <para>

    </para>

    <!--
    In main( ), the try block is within a for loop, so all the possibilities
    are exercised. In this way, you can achieve something like
    resumption. Nest the try block inside a for, while, do, or if and cause
    any exceptions to attempt to repair the problem; then attempt the try
    block again.
    -->
    <para>

    </para>

    <!--
    Only the Up and Fit exceptions are caught because those are the only
    exceptions that the programmer of f( ) said would be thrown. Version two
    of g( ) causes my_unexpected( ) to be called because f( ) then throws an
    int.
    -->
    <para>

    </para>

    <!--
    In the call to set_unexpected( ), the return value is ignored, but it
    can also be saved in a pointer to function and be restored later, as we
    did in the set_terminate( ) example earlier in this chapter.
    -->
    <para>

    </para>

    <!--
    A typical unexpected handler logs the error and terminates the program
    by calling exit( ). It can, however, throw another exception (or rethrow
    the same exception) or call abort( ). If it throws an exception of a
    type allowed by the function whose specification was originally
    violated, the search resumes at the call of the function with this
    exception specification. (This behavior is unique to unexpected( ).)
    -->
    <para>

    </para>

    <!--
    If the exception thrown from your unexpected handler is not allowed by
    the original function's specification, one of the following occurs:
    -->
    <para>

    </para>

    <!--
    1.  If std::bad_exception (defined in <exception>) was in the function's
    exception specification, the exception thrown from the unexpected
    handler is replaced with a std::bad_exception object, and the search
    resumes from the function as before.
    -->
    <para>

    </para>

    <!--
    2.  If the original function's specification did not include
    std::bad_exception, terminate( ) is called.
    -->
    <para>

    </para>

    <!-- The following program illustrates this behavior: -->
    <para>

    </para>


//: V2C01:BadException.cpp {-bor}


    <!--
    The my_uhandler1( ) handler throws an acceptable exception (A), so
    execution resumes at the first catch, which succeeds. The my_uhandler2(
    ) handler does not throw a valid exception (B), but since g specifies
    bad_exception, the B exception is replaced by a bad_exception object,
    and the second catch also succeeds. Since f does not include
    bad_exception in its specification, my_thandler( ) is called as a
    terminate handler. Here's the output: caught an A from f caught a
    bad_exception from g terminate called
    -->
    <para>

    </para>

    <sect2>
      <!-- Better exception specifications? -->
      <title>¿Mejores especificaciones de excepciones?</title>

      <!--
      You may feel that the existing exception specification rules aren't very
      safe, and that
      -->


<programlisting>
void f();
</programlisting>


      <!--
      should mean that no exceptions are thrown from this function. If the
      programmer wants to throw any type of exception, you might think he or
      she should have to say
      -->


<programlisting>
 void f() throw(...); // Not in C++
</programlisting>


      <!--
      This would surely be an improvement because function declarations would
      be more explicit. Unfortunately, you can't always know by looking at the
      code in a function whether an exception will be thrown-it could happen
      because of a memory allocation, for example. Worse, existing functions
      written before exception handling was introduced into the language may
      find themselves inadvertently throwing exceptions because of the
      functions they call (which might be linked into new, exception-throwing
      versions). Hence, the uninformative situation whereby void f();
      -->
      <para>

      </para>

      <!--
      means, "Maybe I'll throw an exception, maybe I won't." This ambiguity is
      necessary to avoid hindering code evolution. If you want to specify that
      f throws no exceptions, use the empty list, as in: void f() throw();
      -->
      <para>

      </para>

    </sect2>
    <sect2>
      <!-- Exception specifications and inheritance -->
      <title>Especificación de excepciones y herencia</title>

      <!--
      Each public function in a class essentially forms a contract with the
      user; if you pass it certain arguments, it will perform certain
      operations and/or return a result. The same contract must hold true in
      derived classes; otherwise the expected "is-a" relationship between
      derived and base classes is violated. Since exception specifications are
      logically part of a function's declaration, they too must remain
      consistent across an inheritance hierarchy. For example, if a member
      function in a base class says it will only throw an exception of type A,
      an override of that function in a derived class must not add any other
      exception types to the specification list because that would break any
      programs that adhere to the base class interface. You can, however,
      specify fewer exceptions or none at all, since that doesn't require the
      user to do anything differently. You can also specify anything that
      "is-a" A in place of A in the derived function's specification. Here's
      an example.
      -->
      <para>

      </para>


//: V2C01:Covariance.cpp {-xo}


      <!--
      A compiler should flag the override of Derived::f( ) with an error (or
      at least a warning) since it changes its exception specification in a
      way that violates the specification of Base::f( ). The specification for
      Derived::g( ) is acceptable because DerivedException "is-a"
      BaseException (not the other way around). You can think of Base/Derived
      and BaseException/DerivedException as parallel class hierarchies; when
      you are in Derived, you can replace references to BaseException in
      exception specifications and return values with DerivedException. This
      behavior is called covariance (since both sets of classes vary down
      their respective hierarchies together). (Reminder from Volume 1:
      parameter types are not covariant-you are not allowed to change the
      signature of an overridden virtual function.)
      -->
      <para>

      </para>

    </sect2>
    <sect2>
      <!-- When not to use exception specifications -->
      <title>Cuándo no usar especificaciones de excepción</title>

      <!--
      If you peruse the function declarations throughout the Standard C++
      library, you'll find that not a single exception specification occurs
      anywhere! Although this might seem strange, there is a good reason for
      this seeming incongruity: the library consists mainly of templates, and
      you never know what a generic type or function might do. For example,
      suppose you are developing a generic stack template and attempt to affix
      an exception specification to your pop function, like this:
      -->
      <para>

      </para>


<programlisting>
T pop() throw(logic_error);
</programlisting>


      <!--
      Since the only error you anticipate is a stack underflow, you might
      think it's safe to specify a logic_error or some other appropriate
      exception type. But type T's copy constructor could throw an
      exception. Then unexpected( ) would be called, and your program would
      terminate. You can't make unsupportable guarantees. If you don't know
      what exceptions might occur, don't use exception specifications. That's
      why template classes, which constitute the majority of the Standard C++
      library, do not use exception specifications-they specify the exceptions
      they know about in documentation and leave the rest to you. Exception
      specifications are mainly for non-template classes.
      -->
      <para>

      </para>

    </sect2>
  </sect1>
  <sect1>
    <!-- Exception safety -->
    <title>Seguridad de la excepción</title>

    <!--
    In Chapter 7 we'll take an in-depth look at the containers in the
    Standard C++ library, including the stack container. One thing you'll
    notice is that the declaration of the pop( ) member function looks like
    this:
    -->
    <para>

    </para>


<programlisting>
void pop();
</programlisting>


    <!--
    You might think it strange that pop( ) doesn't return a value. Instead,
    it just removes the element at the top of the stack. To retrieve the top
    value, call top( ) before you call pop( ). There is an important reason
    for this behavior, and it has to do with exception safety, a crucial
    consideration in library design. There are different levels of exception
    safety, but most importantly, and just as the name implies, exception
    safety is about correct semantics in the face of exceptions.
    -->
    <para>

    </para>

    <!--
    Suppose you are implementing a stack with a dynamic array (we'll call it
    data and the counter integer count), and you try to write pop( ) so that
    it returns a value. The code for such a pop( ) might look something like
    this:
    -->
    <para>

    </para>

<programlisting>
template&lt;class T> T stack&lt;T>::pop() {
  if(count == 0)
    throw logic_error("stack underflow");
  else
    return data[--count];
}
</programlisting>


    <!--
    What happens if the copy constructor that is called for the return value
    in the last line throws an exception when the value is returned? The
    popped element is not returned because of the exception, and yet count
    has already been decremented, so the top element you wanted is lost
    forever! The problem is that this function attempts to do two things at
    once: (1) return a value, and (2) change the state of the stack. It is
    better to separate these two actions into two separate member functions,
    which is exactly what the standard stack class does. (In other words,
    follow the design practice of cohesion-every function should do one
    thing well.) Exception-safe code leaves objects in a consistent state
    and does not leak resources.
    -->
    <para>

    </para>

    <!--
    You also need to be careful writing custom assignment operators. In
    Chapter 12 of Volume 1, you saw that operator= should adhere to the
    following pattern:
    -->
    <para>

    </para>

    <!--
    1.  Make sure you're not assigning to self. If you are, go to step
    6. (This is strictly an optimization.)
    -->
    <para>

    </para>

    <!-- 2.  Allocate new memory required by pointer data members. -->
    <para>

    </para>

    <!-- 3.  Copy data from the old memory to the new. -->
    <para>

    </para>

    <!-- 4.  Delete the old memory. -->
    <para>

    </para>

    <!--
    5.  Update the object's state by assigning the new heap pointers to the
    pointer data members.
    -->
    <para>

    </para>

    <!-- 6.  Return *this. -->
    <para>

    </para>

    <!--
    It's important to not change the state of your object until all the new
    pieces have been safely allocated and initialized. A good technique is
    to move steps 2 and 3 into a separate function, often called clone(
    ). The following example does this for a class that has two pointer
    members, theString and theInts:
    -->
    <para>

    </para>


//: V2C01:SafeAssign.cpp


    <!--
    For convenience, HasPointers uses the MyData class as a handle to the
    two pointers. Whenever it's time to allocate more memory, whether during
    construction or assignment, the first clone function is ultimately
    called to do the job. If memory fails for the first call to the new
    operator, a bad_alloc exception is thrown automatically. If it happens
    on the second allocation (for theInts), we must clean up the memory for
    theString-hence the first try block that catches a bad_alloc
    exception. The second try block isn't crucial here because we're just
    copying ints and pointers (so no exceptions will occur), but whenever
    you copy objects, their assignment operators can possibly cause an
    exception, so everything needs to be cleaned up. In both exception
    handlers, notice that we rethrow the exception. That's because we're
    just managing resources here; the user still needs to know that
    something went wrong, so we let the exception propagate up the dynamic
    chain. Software libraries that don't silently swallow exceptions are
    called exception neutral. Always strive to write libraries that are both
    exception safe and exception neutral.[7]
    -->
    <para>

    </para>

    <!--
    If you inspect the previous code closely, you'll notice that none of the
    delete operations will throw an exception. This code depends on that
    fact. Recall that when you call delete on an object, the object's
    destructor is called. It turns out to be practically impossible to
    design exception-safe code without assuming that destructors don't throw
    exceptions. Don't let destructors throw exceptions. (We're going to
    remind you about this once more before this chapter is done).[8]
    -->
    <para>

    </para>

  </sect1>
  <sect1>
    <!-- Programming with exceptions -->
    <title>Programar con excepciones</title>

    <!--
    For most programmers, especially C programmers, exceptions are not
    available in their existing language and require some adjustment. Here
    are guidelines for programming with exceptions.
    -->
    <para>

    </para>

    <sect2>
      <!-- When to avoid exceptions -->
      <title>Cuándo evitar las excepciones</title>

      <!--
      Exceptions aren't the answer to all problems; overuse can cause
      trouble. The following sections point out situations where exceptions
      are not warranted. The best advice for deciding when to use exceptions
      is to throw exceptions only when a function fails to meet its
      specification.
      -->
      <para>

      </para>

      <!--
      Not for asynchronous events

      The Standard C signal( ) system and any similar system handle
      asynchronous events: events that happen outside the flow of a program,
      and thus events the program cannot anticipate. You cannot use C++
      exceptions to handle asynchronous events because the exception and its
      handler are on the same call stack. That is, exceptions rely on the
      dynamic chain of function calls on the program's runtime stack (they
      have "dynamic scope"), whereas asynchronous events must be handled by
      completely separate code that is not part of the normal program flow
      (typically, interrupt service routines or event loops). Don't throw
      exceptions from interrupt handlers.
      -->
      <para>

      </para>

      <!--
      This is not to say that asynchronous events cannot be associated with
      exceptions. But the interrupt handler should do its job as quickly as
      possible and then return. The typical way to handle this situation is to
      set a flag in the interrupt handler, and check it synchronously in the
      mainline code.
      -->
      <para>

      </para>

      <!--
      Not for benign error conditions

      If you have enough information to handle an error, it's not an
      exception. Take care of it in the current context rather than throwing
      an exception to a larger context.
      -->
      <para>

      </para>

      <!--
      Also, C++ exceptions are not thrown for machine-level events such as
      divide-by-zero.[9] It's assumed that some other mechanism, such as the
      operating system or hardware, deals with these events. In this way, C++
      exceptions can be reasonably efficient, and their use is isolated to
      program-level exceptional conditions.
      -->
      <para>

      </para>

      <!--
      Not for flow-of-control

      An exception looks somewhat like an alternate return mechanism and
      somewhat like a switch statement, so you might be tempted to use an
      exception instead of these ordinary language mechanisms. This is a bad
      idea, partly because the exception-handling system is significantly less
      efficient than normal program execution. Exceptions are a rare event, so
      the normal program shouldn't pay for them. Also, exceptions from
      anything other than error conditions are quite confusing to the user of
      your class or function.
      -->
      <para>

      </para>

      <!--
      You're not forced to use exceptions

      Some programs are quite simple (small utilities, for example). You might
      only need to take input and perform some processing. In these programs,
      you might attempt to allocate memory and fail, try to open a file and
      fail, and so on. It is acceptable in these programs to display a message
      and exit the program, allowing the system to clean up the mess, rather
      than to work hard to catch all exceptions and recover all the resources
      yourself. Basically, if you don't need exceptions, you're not forced to
      use them.
      -->
      <para>

      </para>

      <!--
      New exceptions, old code

      Another situation that arises is the modification of an existing program
      that doesn't use exceptions. You might introduce a library that does use
      exceptions and wonder if you need to modify all your code throughout the
      program. Assuming you have an acceptable error-handling scheme already
      in place, the most straightforward thing to do is surround the largest
      block that uses the new library (this might be all the code in main( ))
      with a try block, followed by a catch(...) and basic error message). You
      can refine this to whatever degree necessary by adding more specific
      handlers, but, in any case, the code you must add can be minimal. It's
      even better to isolate your exception-generating code in a try block and
      write handlers to convert the exceptions into your existing
      error-handling scheme.
      -->
      <para>

      </para>

      <!--
      It's truly important to think about exceptions when you're creating a
      library for someone else to use, especially if you can't know how they
      need to respond to critical error conditions (recall the earlier
      discussions on exception safety and why there are no exception
      specifications in the Standard C++ Library).
      -->
      <para>

      </para>

    </sect2>
    <sect2>
      <!-- Typical uses of exceptions -->
      <title>Usos típicos de excepciones</title>

      <!-- Do use exceptions to do the following: -->
      <para>

      </para>

      <!-- · Fix the problem and retry the function that caused the
      exception. -->
      <para>

      </para>

      <!-- · Patch things up and continue without retrying the
      function. -->
      <para>

      </para>

      <!--
      · Do whatever you can in the current context and rethrow the same
      exception to a higher context.
      -->
      <para>

      </para>

      <!--
      · Do whatever you can in the current context and throw a different
      exception to a higher context.
      -->
      <para>

      </para>

      <!-- · Terminate the program. -->
      <para>

      </para>

      <!--
      · Wrap functions (especially C library functions) that use ordinary
      error schemes so they produce exceptions instead.
      -->
      <para>

      </para>

      <!--
      · Simplify. If your error handling scheme makes things more complicated,
      it is painful and annoying to use. Exceptions can be used to make
      error handling simpler and more effective.
      -->
      <para>

      </para>

      <!--
      · Make your library and program safer. This is a short-term investment
      (for debugging) and a long-term investment (for application robustness).
      -->
      <para>

      </para>

      <!--
      When to use exception specifications

      The exception specification is like a function prototype: it tells the
      user to write exception-handling code and what exceptions to handle. It
      tells the compiler the exceptions that might come out of this function
      so that it can detect violations at runtime.
      -->
      <para>

      </para>

      <!--
      You can't always look at the code and anticipate which exceptions will
      arise from a particular function. Sometimes, the functions it calls
      produce an unexpected exception, and sometimes an old function that
      didn't throw an exception is replaced with a new one that does, and you
      get a call to unexpected( ). Any time you use exception specifications
      or call functions that do, consider creating your own unexpected( )
      function that logs a message and then either throws an exception or
      aborts the program.
      -->
      <para>

      </para>

      <!--
      As we explained earlier, you should avoid using exception specifications
      in template classes, since you can't anticipate what types of exceptions
      the template parameter classes might throw.
      -->
      <para>

      </para>

      <!--
      Start with standard exceptions

      Check out the Standard C++ library exceptions before creating your
      own. If a standard exception does what you need, chances are it's a lot
      easier for your user to understand and handle.
      -->
      <para>

      </para>

      <!--
      If the exception type you want isn't part of the standard library, try
      to inherit one from an existing standard exception. It's nice if your
      users can always write their code to expect the what( ) function defined
      in the exception( ) class interface.
      -->
      <para>

      </para>

      <!--
      Nest your own exceptions

      If you create exceptions for your particular class, it's a good idea to
      nest the exception classes either inside your class or inside a
      namespace containing your class, to provide a clear message to the
      reader that this exception is only for your class. In addition, it
      prevents pollution of the global namespace.
      -->
      <para>

      </para>

      <!--
      You can nest your exceptions even if you're deriving them from C++
      Standard exceptions.
      -->
      <para>

      </para>

      <!--
      Use exception hierarchies

      Using exception hierarchies is a valuable way to classify the types of
      critical errors that might be encountered with your class or
      library. This gives helpful information to users, assists them in
      organizing their code, and gives them the option of ignoring all the
      specific types of exceptions and just catching the base-class
      type. Also, any exceptions added later by inheriting from the same base
      class will not force all existing code to be rewritten-the base-class
      handler will catch the new exception.
      -->
      <para>

      </para>

      <!--
      The Standard C++ exceptions are a good example of an exception
      hierarchy. Build your exceptions on top of it if you can.
      -->
      <para>

      </para>

      <!--
      Multiple inheritance (MI)

      As you'll read in Chapter 9, the only essential place for MI is if you
      need to upcast an object pointer to two different base classes-that is,
      if you need polymorphic behavior with both of those base classes. It
      turns out that exception hierarchies are useful places for multiple
      inheritance because a base-class handler from any of the roots of the
      multiply inherited exception class can handle the exception.
      -->
      <para>

      </para>

      <!--
      Catch by reference, not by value

      As you saw in the section "Exception matching," you should catch
      exceptions by reference for two reasons:
      -->
      <para>

      </para>

      <!--
      · To avoid making a needless copy of the exception object when it is
      passed to the handler.
      -->
      <para>

      </para>

      <!--
      · To avoid object slicing when catching a derived exception as a base
      class object.
      -->
      <para>

      </para>

      <!--
      Although you can also throw and catch pointers, by doing so you
      introduce more coupling-the thrower and the catcher must agree on how
      the exception object is allocated and cleaned up. This is a problem
      because the exception itself might have occurred from heap
      exhaustion. If you throw exception objects, the exception-handling
      system takes care of all storage.
      -->
      <para>

      </para>

      <!--
      Throw exceptions in constructors

      Because a constructor has no return value, you've previously had two
      ways to report an error during construction:
      -->
      <para>

      </para>

      <!-- · Set a nonlocal flag and hope the user checks it. -->
      <para>

      </para>

      <!-- · Return an incompletely created object and hope the user checks it. -->
      <para>

      </para>

      <!--
      This problem is serious because C programmers expect that object
      creation is always successful, which is not unreasonable in C because
      the types are so primitive. But continuing execution after construction
      fails in a C++ program is a guaranteed disaster, so constructors are one
      of the most important places to throw exceptions-now you have a safe,
      effective way to handle constructor errors. However, you must also pay
      attention to pointers inside objects and the way cleanup occurs when an
      exception is thrown inside a constructor.
      -->
      <para>

      </para>

      <!--
      Don't cause exceptions in destructors

      Because destructors are called in the process of throwing other
      exceptions, you'll never want to throw an exception in a destructor or
      cause another exception to be thrown by some action you perform in the
      destructor. If this happens, a new exception can be thrown before the
      catch-clause for an existing exception is reached, which will cause a
      call to terminate( ).
      -->
      <para>

      </para>

      <!--
      If you call any functions inside a destructor that can throw exceptions,
      those calls should be within a try block in the destructor, and the
      destructor must handle all exceptions itself. None must escape from the
      destructor.
      -->
      <para>

      </para>

      <!--
      Avoid naked pointers

      See Wrapped.cpp earlier in this chapter. A naked pointer usually means
      vulnerability in the constructor if resources are allocated for that
      pointer. A pointer doesn't have a destructor, so those resources aren't
      released if an exception is thrown in the constructor. Use auto_ptr or
      other smart pointer types[10] for pointers that reference heap memory.
      -->
      <para>

      </para>

    </sect2>
  </sect1>
  <sect1>
    <!-- Overhead -->
    <title>Sobrecarga</title>

    <!--
    When an exception is thrown, there's considerable runtime overhead (but
    it's good overhead, since objects are cleaned up automatically!). For
    this reason, you never want to use exceptions as part of your normal
    flow-of-control, no matter how tempting and clever it may
    seem. Exceptions should occur only rarely, so the overhead is piled on
    the exception and not on the normally executing code. One of the
    important design goals for exception handling was that it could be
    implemented with no impact on execution speed when it wasn't used; that
    is, as long as you don't throw an exception, your code runs as fast as
    it would without exception handling. Whether this is true depends on the
    particular compiler implementation you're using. (See the description of
    the "zero-cost model" later in this section.)
    -->
    <para>

    </para>

    <!--
    You can think of a throw expression as a call to a special system
    function that takes the exception object as an argument and backtracks
    up the chain of execution. For this to work, extra information needs to
    be put on the stack by the compiler, to aid in stack unwinding. To
    understand this, you need to know about the runtime stack.
    -->
    <para>

    </para>

    <!--
    Whenever a function is called, information about that function is pushed
    onto the runtime stack in an activation record instance (ARI), also
    called a stack frame. A typical stack frame contains the address of the
    calling function (so execution can return to it), a pointer to the ARI
    of the function's static parent (the scope that lexically contains the
    called function, so variables global to the function can be accessed),
    and a pointer to the function that called it (its dynamic parent). The
    path that logically results from repetitively following the dynamic
    parent links is the dynamic chain, or call chain, that we've mentioned
    previously in this chapter. This is how execution can backtrack when an
    exception is thrown, and it is the mechanism that makes it possible for
    components developed without knowledge of one another to communicate
    errors at runtime.
    -->
    <para>

    </para>

    <!--
    To enable stack unwinding for exception handling, extra
    exception-related information about each function needs to be available
    for each stack frame. This information describes which destructors need
    to be called (so that local objects can be cleaned up), indicates
    whether the current function has a try block, and lists which exceptions
    the associated catch clauses can handle. There is space penalty for this
    extra information, so programs that support exception handling can be
    somewhat larger than those that don't.[11] Even the compile-time size of
    programs using exception handling is greater, since the logic of how to
    generate the expanded stack frames during runtime must be generated by
    the compiler.
    -->
    <para>

    </para>

    <!--
    To illustrate this, we compiled the following program both with and
    without exception-handling support in Borland C++ Builder and Microsoft
    Visual C++:[12]
    -->
    <para>

    </para>


//: V2C01:HasDestructor.cpp {O}


    <!--
    If exception handling is enabled, the compiler must keep information
    about ~HasDestructor( ) available at runtime in the ARI for f( ) (so it
    can destroy h properly should g( ) throw an exception). The following
    table summarizes the result of the compilations in terms of the size of
    the compiled (.obj) files (in bytes).
    -->
    <para>

    </para>

    <!--
    Compiler\Mode

    With Exception Support

    Without Exception Support
    -->
    <para>

    </para>

    <!-- Borland -->
    <!-- 616 -->
    <!-- 234 -->
    <para>

    </para>

    <!-- Microsoft -->
    <!-- 1162 -->
    <!-- 680 -->
    <para>

    </para>

    <!--
    Don't take the percentage differences between the two modes too
    seriously. Remember that exceptions (should) typically constitute a
    small part of a program, so the space overhead tends to be much smaller
    (usually between 5 and 15 percent).
    -->
    <para>

    </para>

    <!--
    This extra housekeeping slows down execution, but a clever compiler
    implementation avoids this. Since information about exception-handling
    code and the offsets of local objects can be computed once at compile
    time, such information can be kept in a single place associated with
    each function, but not in each ARI. You essentially remove exception
    overhead from each ARI and thus avoid the extra time to push them onto
    the stack. This approach is called the zero-cost model[13] of exception
    handling, and the optimized storage mentioned earlier is known as the
    shadow stack.[14]
    -->
    <para>

    </para>

  </sect1>
  <sect1>
    <!-- Summary -->
    <title>Resumen</title>

    <!--
    Error recovery is a fundamental concern for every program you
    write. It's especially important in C++ when creating program components
    for others to use. To create a robust system, each component must be
    robust.
    -->
    <para>

    </para>

    <!--
    The goals for exception handling in C++ are to simplify the creation of
    large, reliable programs using less code than currently possible, with
    more confidence that your application doesn't have an unhandled
    error. This is accomplished with little or no performance penalty and
    with low impact on existing code.
    -->
    <para>

    </para>

    <!--
    Basic exceptions are not terribly difficult to learn; begin using them
    in your programs as soon as you can. Exceptions are one of those
    features that provide immediate and significant benefits to your
    project.
    -->
    <para>

    </para>

  </sect1>
  <sect1>
    <!-- Exercises -->
    <title>Ejercicios</title>

    <!--
    Solutions to selected exercises can be found in the electronic document
    The Thinking in C++ Volume 2 Annotated Solution Guide, available for a
    small fee from www.MindView.net.
    -->
    <para>

    </para>

    <!--
    1.  Write three functions: one that returns an error value to indicate
    an error condition, one that sets errno, and one that uses signal(
    ). Write code that calls these functions and responds to the errors. Now
    write a fourth function that throws an exception. Call this function and
    catch the exception. Describe the differences between these four
    approaches, and why exception handling is an improvement.
    -->
    <para>

    </para>

    <!--
    2.  Create a class with member functions that throw exceptions. Within
    this class, make a nested class to use as an exception object. It takes
    a single const char* as its argument; this represents a description
    string. Create a member function that throws this exception. (State this
    in the function's exception specification.) Write a try block that calls
    this function and a catch clause that handles the exception by
    displaying its description string.
    -->
    <para>

    </para>

    <!--
    3.  Rewrite the Stash class from Chapter 13 of Volume 1 so that it
    throws out_of_range exceptions for operator[ ].
    -->
    <para>

    </para>

    <!--
    4.  Write a generic main( ) that takes all exceptions and reports them
    as errors.
    -->
    <para>

    </para>

    <!--
    5.  Create a class with its own operator new. This operator should
    allocate ten objects, and on the eleventh object "run out of memory" and
    throw an exception. Also add a static member function that reclaims this
    memory. Now create a main( ) with a try block and a catch clause that
    calls the memory-restoration routine. Put these inside a while loop, to
    demonstrate recovering from an exception and continuing execution.
    -->
    <para>

    </para>

    <!--
    6.  Create a destructor that throws an exception, and write code to
    prove to yourself that this is a bad idea by showing that if a new
    exception is thrown before the handler for the existing one is reached,
    terminate( ) is called.
    -->
    <para>

    </para>

    <!--
    7.  Prove to yourself that all exception objects (the ones that are
    thrown) are properly destroyed.
    -->
    <para>

    </para>

    <!--
    8.  Prove to yourself that if you create an exception object on the heap
    and throw the pointer to that object, it will not be cleaned up.
    -->
    <para>

    </para>

    <!--
    9.  Write a function with an exception specification that can throw four
    exception types: a char, an int, a bool, and your own exception
    class. Catch each in main( ) and verify the catch. Derive your exception
    class from a standard exception. Write the function in such a way that
    the system recovers and tries to execute it again.
    -->
    <para>

    </para>

    <!--
    10.  Modify your solution to the previous exercise to throw a double
    from the function, violating the exception specification. Catch the
    violation with your own unexpected handler that displays a message and
    exits the program gracefully (meaning abort( ) is not called).
    -->
    <para>

    </para>

    <!--
    11.  Write a Garage class that has a Car that is having troubles with
    its Motor. Use a function-level try block in the Garage class
    constructor to catch an exception (thrown from the Motor class) when its
    Car object is initialized. Throw a different exception from the body of
    the Garage constructor's handler and catch it in main( ).
    -->
    <para>

    </para>
  </sect1>
</chapter>