meo*_*hia 67 php error-handling try-catch
我想抓住这个错误:
$a[1] = 'jfksjfks';
try {
$b = $a[0];
} catch (\Exception $e) {
echo "jsdlkjflsjfkjl";
}
Run Code Online (Sandbox Code Playgroud)
编辑:事实上,我在以下行中收到此错误:
$parse = $xml->children[0]->children[0]->toArray();
zer*_*kms 99
您需要定义自定义错误处理程序,如:
<?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";
}
Run Code Online (Sandbox Code Playgroud)
Mac*_*ade 22
你不能使用try/catch块,因为这是一个错误,而不是例外.
始终在使用前尝试偏移:
if( isset( $a[ 0 ] ) { $b = $a[ 0 ]; }
Run Code Online (Sandbox Code Playgroud)
ggd*_*ras 10
我知道这是2016年,但万一有人上了这篇文章.
您可以使用该array_key_exists($index, $array)方法以避免发生异常.
$index = 99999;
$array = [1,2,3,4,5,6];
if(!array_key_exists($index, $array))
{
//Throw myCustomException;
}
Run Code Online (Sandbox Code Playgroud)
$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();
}
Run Code Online (Sandbox Code Playgroud)
或者,没有创建非常临时的异常的低效率:
$a[1] = 'jfksjfks';
$offset = 0;
if(isset($a[$offset]))
$b = $a[$offset];
else
echo "Notice: Undefined offset: ".$offset;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75833 次 |
| 最近记录: |