PHP:捕获exception并继续执行,这可能吗?

是否有可能发现exception并继续执行脚本?

当然,只要赶上你想继续执行的例外…

try { SomeOperation(); } catch (SomeException $e) { // do nothing... php will ignore and continue } 

当然,这有一个沉默地放弃可能是一个非常重要的错误的问题。 SomeOperation()可能会失败导致其他细微的,很难找出问题,但你永远不会知道你是否默默地放弃exception。

是的,但这取决于你想要执行什么:

例如

 try { a(); b(); } catch(Exception $e){ } c(); 

c()将一直执行。 但是如果a()抛出exception, b() 不会被执行。

只把东西放到相互依赖的try块中。 例如b取决于某个结果,在try-catch块之后放置b是没有意义的。

当然:

 try { throw new Exception('Something bad'); } catch (Exception $e) { // Do nothing } 

您可能想要阅读有关例外情况的PHP文档。

是。

 try { Somecode(); catch (Exception $e) { // handle or ignore exception here. } 

但是请注意,PHP也有错误代码从exception分开,遗留之前从PHP有原始的oop。 大多数库buildin仍然会引发错误代码,而不是例外。 要忽略错误代码,请调用带有@前缀的函数:

 @myfunction(); 

另一个angular度是从处理代码返回一个exception,而不是抛出一个。

我需要用我正在编写的模板框架来做到这一点。 如果用户试图访问数据中不存在的属性,我在处理函数中从深处返回错误,而不是抛出它。

然后,在调用代码中,我可以决定是否抛出这个返回的错误,导致try()catch(),或者只是继续:

 // process the template try { // this function will pass back a value, or a TemplateExecption if invalid $result = $this->process($value); // if the result is an error, choose what to do with it if($result instanceof TemplateExecption) { if(DEBUGGING == TRUE) { throw($result); // throw the original error } else { $result = NULL; // ignore the error } } } // catch TemplateExceptions catch(TemplateException $e) { // handle template exceptions } // catch normal PHP Exceptions catch(Exception $e) { // handle normal exceptions } // if we get here, $result was valid, or ignored return $result; 

这样做的结果是我仍然得到原始错误的上下文,即使它被抛在最上面。

另一个select可能是返回一个自定义的NullObject或一个UnknownProperty对象,并在决定跳过catch()之前与之进行比较,但是因为您可以重新抛出错误,而且如果您完全控制整体结构,认为这是一个干净利落的问题,不能继续尝试/捕捉。

一个古老的问题,但是当我从过去的VBA scipt到PHP,在那里你可以让我们“去”重新进入一个循环“错误”与“简历”,离开它仍然处理function。
在php中,经过一些试验和错误之后,我现在使用嵌套try {} catch {}来处理关键和非关键stream程,甚至是相互依赖的类调用,这样我就可以追溯到错误的开始。 例如,如果函数b依赖于函数a,但函数c是一个很好的但不应该停止的过程,我仍然想知道所有3的结果无论如何,这是我做的:

 //set up array to capture output of all 3 functions $resultArr = array(array(), array(), array()); // Loop through the primary array and run the functions foreach($x as $key => $val) { try { $resultArr[$key][0][] = a($key); $resultArr[$key][1][] = b($val); try { // If successful, output of c() is captured $resultArr[$key][2][] = c($key, $val); } catch(Exception $ex) { // If an error, capture why c() failed $resultArr[$key][2][] = $ex->getMessage(); } } catch(Exception $ex) { // If critical functions a() or b() fail, we catch the reason why $criticalError = $ex->getMessage(); } } 

现在我可以遍历每个键的结果数组并评估结果。 如果()或b()存在严重故障。
在$ resultArr发生严重故障之前,我还有一个参考点,如果exception处理程序设置正确,我知道是否是()或b()失败。
如果c()失败,循环继续。 如果c()在各个点失败了,再加上一些额外的后循环逻辑,我甚至可以通过询问$ resultArr [$ key] [2]来查明c()是否工作或每次迭代都有错误。