我想捕获这个错误:
$a[1] = 'jfksjfks';
try {
$b = $a[0];
} catch (\Exception $e) {
echo "jsdlkjflsjfkjl";
}
编辑:事实上,我在下面这行代码中遇到了错误:
$parse = $xml->children[0]->children[0]->toArray();
我想捕获这个错误:
$a[1] = 'jfksjfks';
try {
$b = $a[0];
} catch (\Exception $e) {
echo "jsdlkjflsjfkjl";
}
编辑:事实上,我在下面这行代码中遇到了错误:
$parse = $xml->children[0]->children[0]->toArray();
你需要定义自己的错误处理程序,例如:
<?php
set_error_handler('exceptions_error_handler');
function exceptions_error_handler($severity, $message, $filename, $lineno) {
if (error_reporting() == 0) {
return;
}
if (error_reporting() & $severity) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
}
$a[1] = 'jfksjfks';
try {
$b = $a[0];
} catch (Exception $e) {
echo "jsdlkjflsjfkjl";
}
使用try/catch块无法捕获这个错误,因为这是一个错误而不是异常。
在使用偏移量之前,始终先检查它们:
if( isset( $a[ 0 ] ) { $b = $a[ 0 ]; }
empty()
而不是 isset()
,因为它们的比较略有不同:https://www.php.net/manual/en/types.comparisons.php - Abraham Brookes我知道现在已经是2016年,但以防万一有人看到了这篇文章。
你可以使用array_key_exists($index, $array)
方法来避免出现异常。
$index = 99999;
$array = [1,2,3,4,5,6];
if(!array_key_exists($index, $array))
{
//Throw myCustomException;
}
$a[1] = 'jfksjfks';
try {
$offset = 0;
if(isset($a[$offset]))
$b = $a[$offset];
else
throw new Exception("Notice: Undefined offset: ".$offset);
} catch (Exception $e) {
echo $e->getMessage();
}
或者,不需要创建一个非常临时的异常导致低效率:
$a[1] = 'jfksjfks';
$offset = 0;
if(isset($a[$offset]))
$b = $a[$offset];
else
echo "Notice: Undefined offset: ".$offset;
echo
放在 else
子句中时。这并不会削弱你的答案,但我认为需要指出来。 - paxdiablo重要提示:尽量不要使用此方法,使用其他方法更好。虽然它可以工作,但它很丑陋,并且有自己的缺陷,比如将真实和有意义的输出转换为异常。
通常情况下,你无法通过简单的 try-catch 块捕获通知。但是有一种 hacky 和丑陋的方法可以做到:
function convert_notice_to_exception($output)
{
if (($noticeStartPoint = \strpos($output, "<b>Notice</b>:")) !== false) {
$position = $noticeStartPoint;
for ($i = 0; $i < 3; $i++)
$position = strpos($output, "</b>", $position) + 1;
$noticeEndPoint = $position;
$noticeLength = $noticeEndPoint + 3 - $noticeStartPoint;
$noticeMessage = \substr($output, $noticeStartPoint, $noticeLength);
throw new \Exception($noticeMessage);
} else
echo $output;
}
try {
ob_start();
// Codes here
$codeOutput = ob_get_clean();
convert_notice_to_exception($codeOutput);
} catch (\Exception $exception) {
}
此外,您还可以使用此函数来捕获警告。只需将函数名称更改为convert_warning_to_exception
,并将"<b>Notice</b>:"
更改为"<b>Warning</b>:"
。
注意:该函数将捕获包含以下内容的正常输出:
<b>Notice</b>:
<b>Notice:</b>
我不确定为什么会出现错误,但我已经修复了一些问题。
在html2pdf.class.php文件中
第2132行:
//FIX:
$ctop=$corr[$y][$x][2]<=count($sw)?$corr[$y][$x][2]:count($sw);
$s = 0; for ($i=0; $i<$ctop; $i++) {$s+= array_key_exists($x+$i, $sw)? $sw[$x+$i]:0;}
在第2138行的SAME:
//FIX:
$ctop=$corr[$y][$x][2]<=count($sw)?$corr[$y][$x][2]:count($sw);
for ($i=0; $i<$ctop; $i++) {
问题是数组$sw没有$corr[$y][$x][2]的键,所以我修复了循环,将其修复到max count($sw)。
我不知道这是否会产生其他后果,但我解决了我的问题,不再有任何错误。
所以我希望它对你也有用..!!! 最好的问候
set_error_handler(...)
放在function exceptions_error_handler...
之后,无论如何感谢。 - TechDogLover OR kiaNasirzadeh