1.抛出和捕获异常
(1)
定义异常类的头文件。
(2)抛出异常对象 throw exception()
(3)向量的使用(整型)
vector
myInts;
for (int i = 0; i < 10; i++)
{
myInts.push_back(i);// 增加元素
cout << myInts[i];
}
(4)string 风格的字符串转换成 C 风格的字符串
string myString = "string style string";
char* cStyleStrng = myString.c_str();
(5)捕获运行时异常
try
{
...
}
catch (const runtime_error& e)
{
...
}
(6)抛出和捕获无效参数异常
throw invalid_argument("");
try
{
...
}
catch (const invalid_argument& e)
{
...
}
注: runtime_error 和 invalid_argument 定义在头文件 中
(7)匹配任何异常(...)
try
{
// code omitted here
}
catch (...)
{
// code omitted
}
注: 不建议使用这种方式
(8)使用抛出列表
1)抛出列表: 一个函数或方法能抛出的异常列表
2)必须为函数声明和实现都提供抛出列表
3)没有抛出列表就可以抛出任何异常
4)空的抛出列表不允许抛出任何异常
(9)在覆盖方法中修改参数列表
1)从列表中删除异常
2)增加超类抛出列表中异常的子类
3)不能完全删除抛出列表
(10)显示异常消息
可调用 exception 或子类的 what() 方法显示捕获到的异常消息
示例:
try
{
...
}
catch (const exception& e)
{
cerr << e.what() << endl;
exit(1);
}
(11)多态地捕获异常
1)在多态地捕获异常时,要确保按引用捕获异常。如果按值捕获异常,就会遇到切割问题,丢失对象的信息。
2)按引用捕获异常可以避免不必要的复制开销
(12)如果异常处理不够仔细,就会导致内存和资源泄漏
示例
func ()
{
string str1;
string* str2 = new string();
throw exception();
delete str2; // 内存泄漏
}
(13)使用智能指针防止内存泄漏
#include
// 定义智能指针的头文件
using namespace std;
func ()
{
string str1;
// 智能指针,不用自己手动释放
auto_ptr
str2(new string("hello"));
throw exception();
}
(14)处理内存分配错误
1)new 和 new [] 分配内存失败默认抛出 bad_alloc 异常
2)可用 try/catch 捕获异常处理内存分配失败
3)示例:
try
{
ptr = new int[numInts];
}
catch (bad_alloc& e)
{
cerr << "Unable to alloc memory!" << endl;
return ;
}
或
1)用 new(nothrow) 在内存分配失败时返回 NULL 来处理
2)示例:
ptr = new(nothrow) int[numInts];
if (ptr == NULL)
{
cerr << "Unable to alloc memory!" << endl;
return;
}
或
1)用 set_new_handler() 回调函数定制分配失败时的行为
2)示例
void myNewHandler()
{
cerr << "Unable to allocate memory!" << endl;
abort(); // 终止程序
}
#include
#include
#include
using namespace std;
int main(int argc, char** argv)
{
new_handler oldHandler = set_new_handler(myNewHandler);
// code omitted here
set_new_handler(oldHandler);
return (0);
}