PHP寮傚父澶勭悊


寮傚父澶勭悊,PHP 5 娣诲姞浜嗙被浼间簬鍏跺畠璇█鐨勫紓甯稿鐞嗘ā鍧椼傚湪 PHP 浠g爜涓墍浜х敓鐨勫紓甯稿彲琚 throw 璇彞鎶涘嚭骞惰 catch 璇彞鎹曡幏銆傞渶瑕佽繘琛屽紓甯稿鐞嗙殑浠g爜閮藉繀椤绘斁鍏 try 浠g爜鍧楀唴锛屼互渚挎崟鑾峰彲鑳藉瓨鍦ㄧ殑寮傚父銆

寮傚父澶勭悊

PHP 5 娣诲姞浜嗙被浼间簬鍏跺畠璇█鐨勫紓甯稿鐞嗘ā鍧椼傚湪 PHP 浠g爜涓墍浜х敓鐨勫紓甯稿彲琚 throw 璇彞鎶涘嚭骞惰 catch 璇彞鎹曡幏銆傞渶瑕佽繘琛屽紓甯稿鐞嗙殑浠g爜閮藉繀椤绘斁鍏 try 浠g爜鍧楀唴锛屼互渚挎崟鑾峰彲鑳藉瓨鍦ㄧ殑寮傚父銆傛瘡涓涓 try 鑷冲皯瑕佹湁涓涓笌涔嬪搴旂殑 catch銆備娇鐢ㄥ涓 catch 鍙互鎹曡幏涓嶅悓鐨勭被鎵浜х敓鐨勫紓甯搞傚綋 try 浠g爜鍧椾笉鍐嶆姏鍑哄紓甯告垨鑰呮壘涓嶅埌 catch 鑳藉尮閰嶆墍鎶涘嚭鐨勫紓甯告椂锛孭HP 浠g爜灏变細鍦ㄨ烦杞埌鏈鍚庝竴涓 catch 鐨勫悗闈㈢户缁墽琛屻傚綋鐒讹紝PHP 鍏佽鍦 catch 浠g爜鍧楀唴鍐嶆鎶涘嚭锛坱hrow锛夊紓甯搞

褰撲竴涓紓甯歌鎶涘嚭鏃讹紝鍏跺悗锛堣瘧鑰呮敞锛氭寚鎶涘嚭寮傚父鏃舵墍鍦ㄧ殑浠g爜鍧楋級鐨勪唬鐮佸皢涓嶄細缁х画鎵ц锛岃 PHP 灏变細灏濊瘯鏌ユ壘绗竴涓兘涓庝箣鍖归厤鐨 catch銆傚鏋滀竴涓紓甯告病鏈夎鎹曡幏锛岃屼笖鍙堟病鐢ㄤ娇鐢 set_exception_handler() 浣滅浉搴旂殑澶勭悊鐨勮瘽锛岄偅涔 PHP 灏嗕細浜х敓涓涓弗閲嶇殑閿欒锛屽苟涓旇緭鍑 Uncaught Exception ... 锛堟湭鎹曡幏寮傚父锛夌殑鎻愮ず淇℃伅銆

Note:

PHP 鍐呴儴鍑芥暟涓昏浣跨敤閿欒鎶ュ憡, 鍙湁鐜颁唬闈㈠悜瀵硅薄鐨勬墿灞曟墠浣跨敤寮傚父銆備絾閿欒鍙互寰堝鏄撶殑閫氳繃ErrorException杞崲涓哄紓甯搞

Tip
PHP鏍囧噯搴 (SPL) 鎻愪緵浜嗚澶氬唴寤虹殑寮傚父绫汇

Example #1 鎶涘嚭涓涓紓甯

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<code><![CDATA[
<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    else return 1/$x;
}
 
try {
    echo inverse(5) . " ";
    echo inverse(0) . " ";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), " ";
}
 
// Continue execution
echo 'Hello World';
?></code>

浠ヤ笂渚嬬▼浼氳緭鍑猴細

1
2
3
0.2
Caught exception: Division by zero.
Hello World

Example #2 宓屽鐨勫紓甯

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<code><?php
 
class MyException extends Exception { }
 
class Test {
    public function testing() {
        try {
            try {
                throw new MyException('foo!');
            } catch (MyException $e) {
                /* rethrow it */
                throw $e;
            }
        } catch (Exception $e) {
            var_dump($e->getMessage());
        }
    }
}
 
$foo = new Test;
$foo->testing();
 
?></code>

浠ヤ笂渚嬬▼浼氳緭鍑猴細

1
string(4) "foo!"

浠ヤ笂灏辨槸PHP寮傚父澶勭悊鐨勮缁嗗唴瀹癸紝鏇村淇℃伅璇峰叧娉∣D浜戝叾瀹冪浉鍏虫枃绔狅紒



鏈枃URL锛http://www.odweb.cn/news_show.html?id=110