爱程序网

异常处理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/**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*/

相关文章列表: