try catch throw php搜集
我个人的理解是:?
1。在private或者protected的成员函数不使用try,catch,而只使用throw?
2。如果在private或者protected的成员函数需要使用try,catch,那么就要使用rethrow?
3。在public成员函数里使用try,catch?
4。如果该类相对于整个项目来说是属于被调用层,那么public成员函数也可以不使用try,catch?
5。如果调用第三方的代码,我一般都会用try,catch?
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;?
? }?
}
//-----------------------------------------------------------------------<div style="line-height: 22px;"><span style="line-height: 22px; color: #0000ff;">try</span><span style="line-height: 22px; color: #000000;"><br style="line-height: 22px;">{<br style="line-height: 22px;">..........<br style="line-height: 22px;">.........<br style="line-height: 22px;"></span><span style="line-height: 22px; color: #008000;">//</span><span style="line-height: 22px; color: #008000;">throw</span><span style="line-height: 22px; color: #008000;"><br style="line-height: 22px;"></span><span style="line-height: 22px; color: #000000;">}<br style="line-height: 22px;"></span><span style="line-height: 22px; color: #0000ff;">catch</span><span style="line-height: 22px; color: #000000;"> (</span><span style="line-height: 22px; color: #0000ff;">int</span><span style="line-height: 22px; color: #000000;"> x)<br style="line-height: 22px;">{<br style="line-height: 22px;">.......<br style="line-height: 22px;">}</span></p>
比如if(..)的 这样的话 要这些try catch干什么?多此一举? 直接if语句后面写就的啦!
(2)如果try中没有throw, 哪么catch 会捕获到异常吗?怎么捕获的?这一点很不明白! 如果try中发生异常 哪么到底谁通知catch呢?
(3) throw到底能干什么?
2.try块里的代码可能没有显示抛出异常,但里面调用的函数有可能抛出异常;怎么捕获的就涉及到异常处理系统的实现,具体的还是由牛人们来解答吧
3.throw就是抛出指定的异常,该异常可以在程序的其他地方被捕获并处理,当然也可能始终没有被捕获,此时,程序一般立刻终止,退出
???
try的代码段假如没有抛出异常(可能是调用的函数抛出异常),catch确实捕获不到异常;用try catch而不用if能够很快的跳出深层嵌套啊。能够让代码更清晰。
(2)
1里提到了可以捕获深层异常,假如调用的函数中抛出了异常,c++会沿调用链向上回溯(不是通过return回溯),找到第一个try块,
然 后找到对应的catch,假如该异常能被catch处理(类型匹配,其中...处理所有异常),则catch块处理该异常,然后按正常程序继续走下去,回 到正常的函数调用返回链。假如一直找不到一个try,catch块,就会调用C++的“未处理异常捕获器”,这个函数指针是可以设置的,他的默认行为是终 止程序。
(3) throw的用处是抛出异常,正常的返回用return,而异常用throw。这样程序可以集中处理返回值(这里的返回值不同于C,每个返回值都是正确的,只是含义不同,而C的返回值可能代表着错误),而错误集中在catch块处理,代码逻辑会更清晰明了
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号