2011-03-21 43 views

回答

76

您需要定義喜歡你的自定義錯誤處理程序:

<?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"; 
} 
+0

如果您關閉了錯誤報告功能,則無法正常工作,因爲您可能會在生產中進行這種操作。 – 2018-03-08 17:16:06

9
$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; 
+8

我笑我們提到創建一個異常是非常低效的,所以你可以立即捕獲它並使用它,特別是當把'echo'放在'else'子句中時更容易。這不會減損你的答案,但我認爲需要指出。 – paxdiablo 2011-03-21 04:31:25

+3

這是非常真實的,我不喜歡寫它,但它足以讓他原來的問題! – Prisoner 2011-03-21 04:34:24

+0

我很想知道downvote,bods背後的基本原理。這對我來說似乎完全沒問題。 – paxdiablo 2011-03-21 04:37:46

20

你不能使用try/catch塊,因爲這是一個錯誤,而不是一個例外。

使用前總是試圖抵消:

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

1.它不是一個錯誤,而是一個通知2.我們可以將通知/警告/錯誤轉化爲例外 – zerkms 2011-03-21 04:33:01

7

我知道這是2016年,但萬一有人得到這個職位。

您可以使用array_key_exists($index, $array)方法,以避免發生異常。

$index = 99999; 
$array = [1,2,3,4,5,6]; 

if(!array_key_exists($index, $array)) 
{ 
    //Throw myCustomException; 
} 
+0

比「if(!$ array [$ index])」更好,謝謝! – user180574 2017-05-19 18:51:50

-3

我敢肯定,爲什麼錯誤拋出,但我解決一些..

在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;} 

SAME ON LINE 2138:

//FIX: 

$ctop=$corr[$y][$x][2]<=count($sw)?$corr[$y][$x][2]:count($sw); 
for ($i=0; $i<$ctop; $i++) { 

問題ar ray $ SW沒有$ corr [$ y] [$ x] [2]的密鑰,所以我修復了最大計數($ sw)來修復的循環.. 我不知道是否創建了另一個通用但我解決我的問題,沒有更多的錯誤..

所以我希望對你有用.. !!! 節拍調節

0

通常情況下,您無法使用try-catch塊捕獲通知。但是你可以將通知轉換爲異常!使用這種方式:

function get_notice($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(); 
    get_notice($codeOutput); 
} catch (\Exception $exception) { 
    // Catch (notice also)! 
} 

此外,您可以使用此功能來捕捉警告。只需將函數名稱更改爲get_warning並將"<b>Notice</b>:"更改爲"<b>Warning</b>:"即可。

注:功能將趕上包含一個無辜的輸出:

<b>通知</B >:

但是從這個問題逃脫,簡單地說,將其更改爲:

<b>提示:</b >