php错误与异常处理
1、file_exist("a.txt") or die("文件不存在");
2、自定义错误函数
<?php
//自定义错误函数
function my_error($err_num.$err_msg){
echo $err_num."<br />";
echo $err_msg;
}
//改写系统错误函数设置
set_error_handler("$my_error",E_WORNING);
//测试函数
fopen("a.txt","r");
?>
3、错误触发函数
<?php
//自定义错误函数
function my_error($err_num.$err_msg){
echo $err_num."<br />";
echo $err_msg;
}
//改写系统错误函数设置
set_error_handler("$my_error",E_WORNING);
//测试函数(一般是逻辑错误)
$age = 700;
if($age > 120){
//调用trigger_error()函数
trigger_error("年龄不在范围内",E_WORNING);
exit();
}
?>
4、错误日志
<?php
//自定义错误函数
function my_error($err_num,$err_msg){
$err_info = "错误号:".$err_num."------错误信息:".$err_msg;
//设置时区
date_default_timezone_set ("Asia/Shanghai");
//记录错误日志 date("Y-m-d H:i:s") H大写表示24小时制,h小写表示12小时制
error_log($err_info.date("Y-m-d H:i:s")."\r\n",3,"b.txt");
}
//改写系统错误函数设置
set_error_handler("$my_error",E_WORNING);
//测试函数
fopen("a.txt","r");
?>
5、异常
//php处理异常
//使用异常机制
<?php
try{
addUser("ss");
}catch(Exception $e ){
//catch捕获 Exception
echo "错误信息:".$e->getMessage();
}
function addUser($userName){
if($userName=="xiaoming"){
//不处理,中国有句话,没有消息就是好消息
}else{
//抛出异常
throw new Exception("名字输入有误");
}
}
?>
5、自定义顶级异常
<?php
//自定义顶级异常处理函数
function my_Exception($e){
echo "错误原因:".$e->getMessage();
}
//修改系统默认顶级异常处理
set_exception_handler("my_Exception");
try{
addUser("xkls");
}catch(Exception $e){
throw $e;
}
function addUser($userName){
if ($userName == "xiaoming") {
# code...
}else{
throw new Exception("名字输入有误");
}
}
?>
6、多个异常处理
<?php
//类的继承
class foException extends Exception{
}
class fcException extends Exception{
}
try{
//addUsera("skdfl");
addUserb("skdfl");
}catch(foException $e1){
echo $e1->getMessage();
}catch(fcException $e2){
echo $e2->getMessage();
}
function addUsera($name){
if ($name=="xiaoming") {
# code...
}else{
throw new foException("a");
}
}
function addUserb($name){
if ($name=="xiaoming") {
# code...
}else{
throw new fcException("b");
}
}
?>