php5.5新增 Finally模塊try { //好好干,出了問題不要怕,外面有人接應(yīng)} catch (HttpException $e) { //時刻準備著,處理上面拋出的HTTP問題} catch (Exception $e) { //時刻準備著,處理他們都處理不了的問題} finally { //打掃戰(zhàn)場,都收拾好了再走人}try 中 return 后 finally 會繼續(xù)執(zhí)行,如果 finally 中也有return,則最終返回值為 finally 中 return 的值。try 中 die 或 exit 后 finally 不會執(zhí)行。example01:
<?php/**finally塊是個很好的設(shè)計,其中的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 的匹配次數(shù)。 它的值將是0次(不匹配)或1次,因為 preg_match() 在第一次匹配后 將會停止搜索。 preg_match_all() 不同于此,它會一直搜索 subject 直到到達結(jié)尾。 如果發(fā)生錯誤 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() . "<br/>"; } echo "The Exception is: " . $e->getMessage() . "<br/>";}
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 8example05
<?php//下面的寫法會報T_THROW Syntax Error.someFunction() OR throw new Exception();//這種寫法可以用下面這個正確的形式function throwException($message = null,$code = null) { throw new Exception($message,$code);}someFunction() OR throwException();新聞熱點
疑難解答