目录
- 一、程序及输出
- 1.1 throw MyException()------catch (MyException e)
- 1.2 throw MyException()------catch (MyException &e)
- 1.3 throw &MyException()------catch (MyException *e)
- 1.4 throw new MyException()------catch (MyException *e)
- 二、分析与总结
一、程序及输出
1.1 throw MyException()------catch (MyException e)
#include<iostream>
using namespace std;
class MyException
{
public:
MyException()
{
cout << "MyException默认构造函数调用" << endl;
}
MyException(const MyException & e)
{
cout << "MyException拷贝构造函数调用" << endl;
}
~MyException()
{
cout << "MyException析构函数调用" << endl;
}
};
void doWork()
{
throw MyException();
}
void test01()
{
try
{
doWork();
}
catch (MyException *e)
{
cout << "自定义异常捕获" << endl;
}
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
输出:
调用拷贝构造函数 效率低
1.2 throw MyException()------catch (MyException &e)
......省略
void doWork()
{
throw MyException();
}
void test01()
{
try
{
doWork();
}
catch (MyException &e)
{
cout << "自定义异常捕获" << endl;
}
}
......省略
输出:
只调用默认构造函数 效率高 推荐
1.3 throw &MyException()------catch (MyException *e)
......省略
void doWork()
{
throw &MyException();
}
void test01()
{
try
{
doWork();
}
catch (MyException *e)
{
cout << "自定义异常捕获" << endl;
}
}
......省略
输出:
对象会提前释放掉,不能再非法操作
1.4 throw new MyException()------catch (MyException *e)
......省略
void doWork()
{
throw new MyException();
}
void test01()
{
try
{
doWork();
}
catch (MyException *e)
{
cout << "自定义异常捕获" << endl;
delete e;
}
}
......省略
输出:
只调用默认构造函数 自己要管理释放
二、分析与总结
抛出的是 throw MyException(); catch (MyException e) 调用拷贝构造函数 效率低
抛出的是 throw MyException(); catch (MyException &e) 只调用默认构造函数 效率高 推荐
抛出的是 throw &MyException(); catch (MyException *e) 对象会提前释放掉,不能再非法操作
抛出的是 new MyException(); catch (MyException *e) 只调用默认构造函数, 自己要管理释放