与java不同,在php中,异常必须手动抛出.
抛出并捕获一个异常,示例:
Exception("A terrible error has occurred",42);
}catch (Exception $e){
echo "Exception ".$e->getCode().":".$e->getMessage()."
"."in".$e->getFile()." on line".$e->getLine()."
";
}显示结果:

Exception类的内置方法:
getCode()——返回传递给构造函数的代码;
立即学习“PHP免费学习笔记(深入)”;
getMessage()——返回传递给狗仔函数的消息;
getFile()——返回产生异常的代码文件的完整路径;
getLine()——返回代码文件中产生异常的代码行号;
getTrance——返回一个包含了产生异常的代码回退路径的数组;
getTranceAsString——返回与getTrance()方向相同的消息,该消息将被格式化一个字符串;
__toString()——允许简单地显示一个Exception对象,并且给出以上所有方法可以提供的信息。
采用 php+mysql 数据库方式运行的强大网上商店系统,执行效率高速度快,支持多语言,模板和代码分离,轻松创建属于自己的个性化用户界面 v3.5更新: 1).进一步静态化了活动商品. 2).提供了一些重要UFT-8转换文件 3).修复了除了网银在线支付其它支付显示错误的问题. 4).修改了LOGO广告管理,增加LOGO链接后主页LOGO路径错误的问题 5).修改了公告无法发布的问题,可能是打压
用户自定义异常示例:
Exception extends Exception{
function __toString(){
return "Exception ".$this->getCode().":".$this->getMessage()."
"."in".$this->getFile()." on line".$this->getLine()."
";
}
}
try{
throw new myException("A terrible error has occurred",42);
}catch (myException $m){
echo $m;
}一个应用异常处理的示例:文件I/O处理
首先需要创建一个异常类的文件:file_Exception.php
Exception extends Exception{
function __toString(){
return "fileOpenException ".$this->getCode().":".$this->getMessage()."
"."in".$this->getFile()." on line".$this->getLine()."
";
}
}
//自定义无法写入异常
class fileWriteException extends Exception{
function __toString(){
return "fileWriteException ".$this->getCode().":".$this->getMessage()."
"."in".$this->getFile()." on line".$this->getLine()."
";
}
}
//自定义无法获得写锁异常
class fileLockException extends Exception{
function __toString(){
return "fileLockException ".$this->getCode().":".$this->getMessage()."
"."in".$this->getFile()." on line".$this->getLine()."
";
}
}再在主文件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 "数据保存完成
";
}catch (fileOpenException $foe){
echo "文件打开失败,请查看服务器是否异常!
";
exit;
}catch(Exception $e){
echo "您的订单没有提交完成,请再试一次。
";
exit;
}以上就介绍了php的错误和异常处理,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。










