php如何自訂異常類,捕獲異常和拋出異常.
或者給個例子參考下
回複討論(解決方案)
try { throw new Exception($error); } catch (Exception $e) { echo $e->getMessage(); }
try{
throw new Exception($error);
}catch(Exception $e){
echo $e->getCode();
}
set_exception_handler('myException');test(-1);function test($a){if($a < 0){throw new Exception('error');}return $a;}function myException($e){$msg='code : '.$e->getCode().'
message : '.$e->getMessage();echo $msg;}
http://www.php.net/manual/zh/language.exceptions.php
function inverse($x) { if (!$x) { throw new Exception('Division by zero.'); } return 1/$x;}try { echo inverse(5) . "\n"; echo inverse(0) . "\n";} catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n";}// Continue executionecho "Hello World\n";以上常式會輸出:0.2Caught exception: Division by zero.Hello World
自訂一個異常類
getMessage()); } }}$foo = new Test;$foo->testing();?>
try {
throw new Exception($error);
} catch (Exception $e) {
echo $e->getMessage();
}
樓上都是正解