異常處理try-catch-finally

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

<?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:java

<?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:c#

<?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() . "<br/>";
        }
        echo "The Exception is: " . $e->getMessage() . "<br/>";
}


example04ide

<?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


example05this

<?php

//下面的寫法會報T_THROW Syntax Error.
someFunction() OR throw new Exception();

//這種寫法能夠用下面這個正確的形式
function throwException($message = null,$code = null) {
    throw new Exception($message,$code);
}

someFunction() OR throwException();
相關文章
相關標籤/搜索