How to catch this error: “Notice: Undefined offset: 0”

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

I want to catch this error:

$a[1] = 'jfksjfks'; try {       $b = $a[0]; } catch (\Exception $e) {       echo "jsdlkjflsjfkjl"; } 

Edit: in fact, I got this error on the following line: $parse = $xml->children[0]->children[0]->toArray();

回答1:

You need to define your custom error handler like:



回答2:

You can't with a try/catch block, as this is an error, not an exception.

Always tries offsets before using them:

if( isset( $a[ 0 ] ) { $b = $a[ 0 ]; } 


回答3:

$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(); } 

Or, without the inefficiency of creating a very temporary exception:

$a[1] = 'jfksjfks'; $offset = 0; if(isset($a[$offset]))   $b = $a[$offset]; else   echo "Notice: Undefined offset: ".$offset; 


回答4:

I know it's 2016 but in case someone gets to this post.

You could use the array_key_exists($index, $array) method in order to avoid the exception to happen.

$index = 99999; $array = [1,2,3,4,5,6];  if(!array_key_exists($index, $array)) {     //Throw myCustomException; } 


回答5:

Normally, you can't catch notices with try-catch block. But you can convert notices to exceptions! Use this way:

function get_notice($output) {     if (($noticeStartPoint = strpos($output, "Notice:")) !== false) {         $position = $noticeStartPoint;         for ($i = 0; $i ", $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();     get_notice($codeOutput); } catch (\Exception $exception) {     // Catch (notice also)! } 

Also, you can use this function for to catch warnings. Just change function name to get_warning and change "Notice:" to "Warning:".

Note: The function will catch an innocent output that contains:

Notice:

But to escape from this problem, simply, change it to:

Notice:



回答6:

Im sure why the Error Throw but i fix some..

in html2pdf.class.php

on Lines 2132:

//FIX: $ctop=$corr[$y][$x][2]

SAME On line 2138:

//FIX:  $ctop=$corr[$y][$x][2]

the problem the array $sw not have a key of $corr[$y][$x][2] so i fix the loop for to max count($sw) to fix .. I dont know if that create an another consecuense but i resolve my problem y dont have any more errors..

So i hope works to you ..!!! Beats Reguards



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!