本文主要是介绍经验分享,如何使用try,catch, throw之一,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
try,catch, throw的含义就很清楚,但怎么使用,我还是过了好多年才明白一些先看一个不好的例子
//----------------- 不好的代码 -----------------
class CTest1;
class CTest2;
class CTest3;
void BadCode()
{
//new test1
CTest1 * pTest1 = new CTest1;
//do something
bool bRet = DoSomething();
if (!bRet)
{
delete pTest1;
return;
}
//new CTest2
CTest2 * pTest2 = new CTest2;
//do something
bRet = DoSomething();
if (!bRet)
{
delete pTest1;
delete pTest2;
return;
}
//new CTest3
CTest3 * pTest3 = new CTest3;
//do something
bRet = DoSomething();
if (!bRet)
{
delete pTest1;
delete pTest2;
delete pTest3;
return;
}
//release
delete pTest1;
delete pTest2;
delete pTest3;
}
下面是我个人比较喜欢的写法
//--------- 好的例子 ---------------
class CTest1;
class CTest2;
class CTest3;
void BadCode()
{
//define
CTest1 * pTest1 = NULL;
CTest2 * pTest2 = NULL;
CTest3 * pTest3 = NULL;
//使用try, catch, throw
try
{
//new test1
pTest1 = new CTest1;
//do something
bool bRet = DoSomething();
if (!bRet)
throw -1;
//new CTest2
pTest2 = new CTest2;
//do something
bRet = DoSomething();
if (!bRet)
throw -2;
//new CTest3
pTest3 = new CTest3;
bRet = DoSomething();
//do something
if (!bRet)
throw -3;
//release
delete pTest1;
pTest1 = NULL;
delete pTest2;
pTest2 = NULL;
delete pTest3;
pTest3 = NULL;
}
catch(...)
{
if (pTest1)
delete pTest1;
if (pTest2)
delete pTest2;
if (pTest3)
delete pTest3;
}
}
简单说一下
第一种写法,需要在不同的地方delete 不同的变量
第二种写法,在catch里delete所有的变量,代码的结构看起来更容易读,也易于维护
//define
CTest1 * pTest1 = NULL;
CTest2 * pTest2 = NULL;
CTest3 * pTest3 = NULL;
变量定义一定要在try之前定义,否则catch里找不到这些变量的定义
这篇关于经验分享,如何使用try,catch, throw之一的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!