与java不同,在php中,异常必须手动抛出.
抛出并捕获一个异常,示例:
<?php
try{
throw new Exception("A terrible error has occurred",42);
}catch (Exception $e){
echo "Exception ".$e->getCode().":".$e->getMessage()."<br/>"."in".$e->getFile()." on line".$e->getLine()."<br/>";
}
显示结果:
Exception类的内置方法:
getCode()——返回传递给构造函数的代码;
getMessage()——返回传递给狗仔函数的消息;
getFile()——返回产生异常的代码文件的完整路径;
getLine()——返回代码文件中产生异常的代码行号;
getTrance——返回一个包含了产生异常的代码回退路径的数组;
getTranceAsString——返回与getTrance()方向相同的消息,该消息将被格式化一个字符串;
__toString()——允许简单地显示一个Exception对象,并且给出以上所有方法可以提供的信息。
用户自定义异常示例:
<?php
//自定义异常
class myException extends Exception{
function __toString(){
return "Exception ".$this->getCode().":".$this->getMessage()."<br/>"."in".$this->getFile()." on line".$this->getLine()."<br/>";
}
}
try{
throw new myException("A terrible error has occurred",42);
}catch (myException $m){
echo $m;
}
一个应用异常处理的示例:文件I/O处理
首先需要创建一个异常类的文件:file_exception.php
<?php
//自定义文件打开异常
class fileOpenException extends Exception{
function __toString(){
return "fileOpenException ".$this->getCode().":".$this->getMessage()."<br/>"."in".$this->getFile()." on line".$this->getLine()."<br/>";
}
}
//自定义无法写入异常
class fileWriteException extends Exception{
function __toString(){
return "fileWriteException ".$this->getCode().":".$this->getMessage()."<br/>"."in".$this->getFile()." on line".$this->getLine()."<br/>";
}
}
//自定义无法获得写锁异常
class fileLockException extends Exception{
function __toString(){
return "fileLockException ".$this->getCode().":".$this->getMessage()."<br/>"."in".$this->getFile()." on line".$this->getLine()."<br/>";
}
}
再在主文件processorder.php文件中引入file.exception.php文件
require_once ("file_exception.php");
异常处理关键代码:
//设置文件输出内容和格式
$out_put_string=$date."\t".$cloths."件男装\t".$shoes."双鞋子\t".$glasses."副眼镜\t\总价:¥".$total_amount." 收货地址:\t".$address."\n";
//异常处理
try{
//打开文件,(追加模式+二进制模式)
if(!($fp=@fopen("$DOCUMENT_ROOT/L02/files/orders.txt",'ab')))
throw new fileOpenException();
//写操作锁定
if(!flock($fp,LOCK_EX))
throw new fileLockException();
//将数据写入到文件
if(!fwrite($fp,$out_put_string,strlen($out_put_string)))
throw new fileWriteException();
//释放已有的锁定
flock($fp,LOCK_UN);
//关闭文件流
fclose($fp);
echo "<p>数据保存完成</p>";
}catch (fileOpenException $foe){
echo "<p><strong>文件打开失败,请查看服务器是否异常!</strong></p>";
exit;
}catch(Exception $e){
echo "<p><strong>您的订单没有提交完成,请再试一次。</strong></p>";
exit;
}