php:捕获异常并继续执行,这可能吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2132759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php: catch exception and continue execution, is it possible?
提问by Kirzilla
Is it possible to catch exception and continue execution of script?
是否可以捕获异常并继续执行脚本?
回答by Felix Kling
Yes but it depends what you want to execute:
是的,但这取决于您要执行的操作:
E.g.
例如
try {
a();
b();
}
catch(Exception $e){
}
c();
c()will always be executed. But if a()throws an exception, b()is notexecuted.
c()将永远被执行。但是如果a()抛出异常,b()则不会被执行。
Only put the stuff in to the tryblock that is depended on each other. E.g. bdepends on some result of ait makes no sense to put bafter the try-catchblock.
只将东西放入相互依赖的try块中。例如,b取决于某些结果,将a其放在块b之后是没有意义的try-catch。
回答by Doug T.
Sure, just catch the exception where you want to continue execution...
当然,只需捕获要继续执行的异常...
try
{
SomeOperation();
}
catch (SomeException $e)
{
// do nothing... php will ignore and continue
}
Of course this has the problem of silently dropping what could be a very important error. SomeOperation() may fail causing other subtle, difficult to figure out problems, but you would never know if you silently drop the exception.
当然,这存在悄悄丢弃可能是非常重要的错误的问题。SomeOperation() 可能会失败,导致其他微妙的、难以解决的问题,但您永远不会知道是否默默地删除异常。
回答by Dominic Rodger
Sure:
当然:
try {
throw new Exception('Something bad');
} catch (Exception $e) {
// Do nothing
}
You might want to go have a read of the PHP documentation on Exceptions.
您可能想要阅读有关Exceptions的 PHP 文档。
回答by Crast
Yes.
是的。
try {
Somecode();
catch (Exception $e) {
// handle or ignore exception here.
}
however note that php also has error codes separate from exceptions, a legacy holdover from before php had oop primitives. Most library builtins still raise error codes, not exceptions. To ignore an error code call the function prefixed with @:
但是请注意,php 还具有与异常分开的错误代码,这是 php 具有 oop 原语之前的遗留保留。大多数库内置函数仍然会引发错误代码,而不是异常。要忽略错误代码,请调用以 @ 为前缀的函数:
@myfunction();
回答by Abdessamad
php > 7
php > 7
use the new interface Throwable
使用新界面 Throwable
try {
// Code that may throw an Exception or Error.
} catch (Throwable $t) {
// Handle exception
}
echo "Script is still running..."; // this script will be executed.
回答by davestewart
Another angle on this is returning an Exception, NOT throwing one, from the processing code.
另一个角度是从处理代码中返回一个异常,而不是抛出一个异常。
I needed to do this with a templating framework I'm writing. If the user attempts to access a property that doesn't exist on the data, I returnthe error from deep within the processing function, rather than throwing it.
我需要使用我正在编写的模板框架来做到这一点。如果用户尝试访问数据中不存在的属性,我会从处理函数的深处返回错误,而不是抛出它。
Then, in the calling code, I can decide whether to throw this returned error, causing the try() to catch(), or just continue:
然后,在调用代码中,我可以决定是抛出这个返回的错误,导致 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;
The result of this is I still get the context of the original error, even though it was thrown at the top.
这样做的结果是我仍然得到原始错误的上下文,即使它被抛出到顶部。
Another option might be to return a custom NullObject or a UnknownProperty object and compare against that before deciding to trip the catch(), but as you can re-throw errors anyway, and if you're fully in control of the overall structure, I think this is a neat way round the issue of not being able to continue try/catches.
另一种选择可能是返回自定义 NullObject 或 UnknownProperty 对象并在决定跳闸 catch() 之前与它们进行比较,但由于您无论如何都可以重新抛出错误,并且如果您完全控制整体结构,我认为这是解决无法继续尝试/捕获问题的巧妙方法。
回答by Roy
An old question, but one I had in the past when coming away from VBA scipts to php, where you could us "GoTo" to re-enter a loop "On Error" with a "Resume" and away it went still processing the function.
In php, after a bit of trial and error, I now use nested try{} catch{} for critical versus non critical processes, or even for interdependent class calls so I can trace my way back to the start of the error.
e.g. if function b is dependant on function a, but function c is a nice to have but should not stop the process, and I still want to know the outcomes of all 3 regardless, here's what I do:
一个老问题,但是我过去从 VBA scipts 转到 php 时遇到的一个问题,您可以在其中使用“GoTo”重新输入带有“Resume”的循环“On Error”,然后它继续处理函数.
在 php 中,经过一些反复试验后,我现在将嵌套的 try{} catch{} 用于关键进程与非关键进程,甚至用于相互依赖的类调用,以便我可以追溯到错误的开始。例如,如果函数 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();
}
}
Now I can loop through my result array for each key and assess the outcomes.
If there is a critical failure for a() or b().
I still have a point of reference on how far it got before a critical failure occurred within the $resultArr and if the exception handler is set correctly, I know if it was a() or b() that failed.
If c() fails, loop keeps going. If c() failed at various points, with a bit of extra post loop logic I can even find out if c() worked or had an error on each iteration by interrogating $resultArr[$key][2].
现在我可以遍历每个键的结果数组并评估结果。如果 a() 或 b() 出现严重故障。
我仍然有一个参考点,它在 $resultArr 中发生严重故障之前有多远,如果异常处理程序设置正确,我知道是 a() 还是 b() 失败了。
如果 c() 失败,循环继续进行。如果 c() 在各个点都失败了,通过一些额外的后循环逻辑,我什至可以通过询问 $resultArr[$key][2] 来确定 c() 是否在每次迭代中工作或有错误。

