Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中良好的错误处理实践-如果函数不';当它应该回来的时候,它不会回来_Php_Error Handling - Fatal编程技术网

PHP中良好的错误处理实践-如果函数不';当它应该回来的时候,它不会回来

PHP中良好的错误处理实践-如果函数不';当它应该回来的时候,它不会回来,php,error-handling,Php,Error Handling,我希望改进PHP程序中的错误处理和调试,需要一些建议。假设我有这个函数(这是完全没有用的,只是编出来的): 如果我告诉C函数的目的是返回某个东西,那么在C中就不允许出现上述情况。这是因为$x可能永远不会等于'something' 这是改善我的功能的一步吗 function foo($bar) { foreach($bar as $x): if($x == 'something') { return 'found something' } en

我希望改进PHP程序中的错误处理和调试,需要一些建议。假设我有这个函数(这是完全没有用的,只是编出来的):

如果我告诉C函数的目的是返回某个东西,那么在C中就不允许出现上述情况。这是因为
$x
可能永远不会等于
'something'

这是改善我的功能的一步吗

function foo($bar) {
   foreach($bar as $x):
      if($x == 'something') {
         return 'found something'
      }
   endforeach;
   throw new Exception('some exception');
}
但仍然不能确保函数返回。。除非抛出一个新的异常返回,但我不这么认为。没有比这更好的方法或错误处理了吗

function foo($bar) {
   foreach($bar as $x):
      if($x == 'something') {
         return 'found something'
      }
   endforeach;
   throw new Exception('some exception');
   return -1; 
}
然后检查函数是否在代码的其他地方返回-1


谢谢:)。

从函数引发异常不允许函数返回。即使是这样,您也没有机会查看返回值,因为PHP将要求立即在catch块中处理异常

如果
$x
永远不能等于
'something'
,则需要返回-1,请不要从函数中抛出任何异常。但是如果要在调用代码返回-1时抛出异常,那么最好忘记返回该值。直接抛出异常,并在调用代码的catch块中处理它


有用的阅读:

谢谢你。。还添加了您作为版主职位的选择。
function foo($bar) {
   foreach($bar as $x):
      if($x == 'something') {
         return 'found something'
      }
   endforeach;
   throw new Exception('some exception');
   return -1; 
}
function Demo()
{
    try
    {
        // Your logic here
    }
    catch(Exception $e)
    {
        error_log($e->getMessege(),3,'error.log');
    }
}