C++中使用catch(…)处理所有异常
在捕获异常方面, try 和 catch 是最重要的 C++关键字。要捕获语句可能引发的异常,可将它们放
在 try 块中,并使用 catch 块对 try 块可能引发的异常进行处理:
void SomeFunc()
{
try
{
int* numPtr = new int;
*numPtr = 999;
delete numPtr;
}
catch(...) // ... catches all exceptions
{
cout << "Exception in SomeFunc(), quitting" << endl;
}
}
成功分配内存时,默认形式的 new 返回一个指向该内存单元的有效指针,但失败时
引发异常。程序清单 28.1 演示了如何捕获使用 new 分配内存时可能引发的异常,并在计算机不能分配
请求的内存时进行处理。
程序清单 28.1 使用 try 和 catch 捕获并处理内存分配异常
0: #include <iostream>
1: using namespace std;
2:
3: int main()
4: {
5: cout << "Enter number of integers you wish to reserve: ";
6: try
7: {
8: int input = 0;
9: cin >> input;
10:
11: // Request memory space and then return it
12: int* numArray = new int [input];
13: delete[] numArray;
14: }
15: catch (...)
16: {
17: cout << "Exception occurred. Got to end, sorry!" << endl;
18: }
19: return 0;
20: }
输出

6615

被折叠的 条评论
为什么被折叠?



