PHP 5 添加了类似于其它语言的异常处理模块。在 PHP 代码中所产生的异常可被 throw 语句抛出并被 catch 语句捕获。需要进行异常处理的代码都必须放入 try 代码块内,以便捕获可能存在的异常。每一个 try 至少要有一个与之对应的 catch。使用多个 catch 可以捕获不同的类所产生的异常。当 try 代码块不再抛出异常或者找不到 catch 能匹配所抛出的异常时,PHP 代码就会在跳转到最后一个 catch 的后面继续执行。当然,PHP 允许在 catch 代码块内再次抛出(throw)异常。
PHP 5提供了基本的异常处理类,可直接使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php
class Exception
{
protected $message = 'Unknown exception' ;
protected $code = 0;
protected $file ;
protected $line ;
function __construct( $message = null, $code = 0);
final function getMessage();
final function getCode();
final function getFile();
final function getLine();
final function getTrace();
final function getTraceAsString();
function __toString();
}
?>
|
Nach dem Login kopieren
通过异常,抛出错误信息:
1 2 3 4 5 6 7 8 | try {
$error = 'my error!' ;
throw new Exception( $error )
}
catch (Exception $e )
{
echo $e ->getMessage();
}
|
Nach dem Login kopieren
我们可以扩展此类,方便我们的使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class MyException extends Exception
{
public function __construct( $message , $code = 0) {
parent::__construct( $message , $code );
}
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n" ;
}
public function customFunction() {
echo "A Custom function for this type of exception\n" ;
}
}
|
Nach dem Login kopieren
这个类可以根据你的需要随意扩展使用。
http://www.bkjia.com/PHPjc/752479.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/752479.htmlTechArticlePHP 5 添加了类似于其它语言的异常处理模块。在 PHP 代码中所产生的异常可被 throw 语句抛出并被 catch 语句捕获。需要进行异常处理的代码都...