PHP寮傚父澶勭悊
寮傚父澶勭悊
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浜戝叾瀹冪浉鍏虫枃绔狅紒