異常處理try-catch-finally_PHP教程

來源:互聯網
上載者:User
php5.5新增 Finally模組

try {
//好好乾,出了問題不要怕,外面有人接應
} catch (HttpException $e) {
//時刻準備著,處理上面拋出的HTTP問題
} catch (Exception $e) {
//時刻準備著,處理他們都處理不了的問題
} finally {
//打掃戰場,都收拾好了再走人
}


try 中 return 後 finally 會繼續執行,如果 finally 中也有return,則最終傳回值為 finally 中 return 的值。
try 中 die 或 exit 後 finally 不會執行。

example01:

php/**finally塊是個很好的設計,其中的return語句能覆蓋其他塊中的return語句,並處理try catch拋出的異常無需try-catch嵌套來處理子try-catch拋出的異常這個跟java的一樣,c#是在finally塊中存在return語句會拋出compile time error(編譯時間錯誤)*/function asdf(){    try {        throw new Exception('error');    }    catch(Exception $e) {        echo "An error occurred";        throw $e;    }    finally {                //This overrides the exception as if it were never thrown        return "\nException erased";    }}try {    echo asdf();}catch(Exception $e) {    echo "\nResult: " . $e->getMessage();}/* The output from above will look like this:     An error occurred     Exception erased Without the return statement in the finally block it would look like this:     An error occurred     Result: error*/


example02:

php/**有個相悖的行為在PHP 5.5.3's finally 和 return statements:在一個方法中,try塊單返回一個變數,finally塊修改這個變數,返回的是finally修改過的,但當try塊返回的變數參與運算(evaluated in-line),會忽略finally塊對這個變數的修改(不知道原因...)*/function returnVariable(){ $foo = 1; try{ return $foo; } finally { $foo++; } } function returnVariablePlusZero(){ $foo = 1; try{ return $foo+0; } finally { $foo++; } } $test1 = returnVariable(); // returns 2, not the correct value of 1. $test2 = returnVariablePlusZero(); // returns correct value of 1, but inconsistent with $test1.


example03:

php/**小例子 驗證變數check if the name contains only letters, and does not contain the word name*/$name = "Name";try{        try        {                //preg_match() 返回 pattern  的匹配次數。 它的值將是0次(不匹配)或1次,因為 preg_match() 在第一次匹配後 將會停止搜尋。 preg_match_all() 不同於此,它會一直搜尋 subject  直到到達結尾。 如果發生錯誤 preg_match() 返回 FALSE 。                if(preg_match('/[^a-z]/i', $name))                {                        throw new Exception("$name contains character other than a-z A-Z");                }                if(strpos(strtolower($name), 'name') !== false)                {                        throw new Exception("$name contains the word name");                }                echo "The Name is valid";        }        catch (exception $e)        {                throw new Exception("insert name again", 0, $e);        }}catch (exception $e){        if($e->getPrevious())        {                echo "The Previous Exception is: " . $e->getPrevious()->getMessage() . "
"; } echo "The Exception is: " . $e->getMessage() . "
";}


example04

php/*When catching an exception inside a namespace it is important that you escape to the global space:如何逃離出命名空間*/ namespace SomeNamespace; class SomeClass {  function SomeFunction() {   try {    throw new Exception('Some Error Message');   } catch (\Exception $e) {    var_dump($e->getMessage());   }  } }//報錯://Fatal error: Class 'SomeNamespace\Exception' not found in C:\xampp\htdocs\tonglei\index.php on line 8


example05

php//下面的寫法會報T_THROW Syntax Error.someFunction() OR throw new Exception();//這種寫法可以用下面這個正確的形式function throwException($message = null,$code = null) {    throw new Exception($message,$code);}someFunction() OR throwException();

http://www.bkjia.com/PHPjc/769758.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/769758.htmlTechArticlephp5.5新增 Finally模組 try { //好好乾,出了問題不要怕,外面有人接應 } catch (HttpException $e) { //時刻準備著,處理上面拋出的HTTP問題 } catch (...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.