一、PHP错误处理的三种方式
1.die()语句,等价于exit()
file_exists('test.txt') or die('文件不存在');
2.自定义错误和错误触发器
a)错误触发器
trigger_error():产生一个用户级别的error/warning/notice信息
<?php
$age = 80;
if($age!=120){
trigger_error("年龄错误");
}
?>
b)自定义错误
创建自定义错误函数(处理器),该函数必须有能力处理至少两个参数(error_level和errormessage),但是可以接受最多五个参数(error_file、error_line、error_context)
set_error-handle('自定义错误处理函数',自定义错误处理级别)
1 <?php 2 date_default_timezone_set('PRC'); 3 function myerror($error_level,$error_message){ 4 $info= "错误号:$error_level "; 5 $info.= "错误信息:$error_message "; 6 $info.= '发生时间:'.date('Y-m-d H:i:s'); 7 $filename='aa.txt'; 8 if(!$fp=fopen($filename,'a')){ 9 '创建文件'.$filename.'失败'; 10 } 11 if(is_writeable($filename)){ 12 if(!fwrite($fp,$info)){ 13 echo '写入文件失败'; 14 } else { 15 echo '已成功记录错误信息'; 16 } 17 fclose($fp); 18 } else { 19 echo '文件'.$filename.'不可写'; 20 } 21 exit(); 22 } 23 set_error_handler('myerror',E_WARNING); 24 $fp=fopen('aaa.txt','r'); 25 ?>
c)错误日志
默认的根据php.ini中error_log配置,php向服务器的错误记录系统或文件发送错误记录。
error_log():发送错误信息到某个地方
1 <?php 2 // 如果无法连接到数据库,发送通知到服务器日志 3 if (!Ora_Logon($username, $password)) { 4 error_log("Oracle database not available!", 0); 5 } 6 7 // 如果用尽了 FOO,通过邮件通知管理员 8 if (!($foo = allocate_new_foo())) { 9 error_log("Big trouble, we're all out of FOOs!", 1, 10 "operator@example.com"); 11 } 12 13 // 调用 error_log() 的另一种方式: 14 error_log("You messed up!", 3, "/var/tmp/my-errors.log"); 15 ?>
二、PHP异常处理
1.基本语法
try{
//可能出现错误或异常的代码
//catch 捕获 Exception是php已定义好的异常类
} catch(Exception $e){
//对异常处理,方法:
//1、自己处理
//2、不处理,将其再次抛出
}
2.处理程序包括:
- Try - 使用异常的函数应该位于 "try" 代码块内。如果没有触发异常,则代码将照常继续执行。但是如果异常被触发,会抛出一个异常。
- Throw - 这里规定如何触发异常。每一个 "throw" 必须对应至少一个 "catch"
- Catch - "catch" 代码块会捕获异常,并创建一个包含异常信息的对象
a)简单示例
1 <?php 2 function checkNum($num){ 3 if($num > 1){ 4 throw new Exception("Value must be 1 or below"); 5 } 6 return true; 7 } 8 try{ 9 checkNum(2); 10 echo "If you see this, the number is 1 or below"; 11 }catch(Exception $e){ 12 echo "Message:".$e->getMessage(); 13 } 14 ?>
程序将会输出:
b)设置顶级异常处理器
1 <?php 2 function myexception($e){ 3 echo "this is top exception"; 4 } 5 set_exception_handler("myexception"); 6 try{ 7 $i=1; 8 if($i<2){ 9 throw new Exception("$i must greater than 10"); 10 } 11 }catch(Exception $e){ 12 echo $e->getMessage().'<br/>'; 13 throw new Exception('errorinfo'); 14 } 15 ?>
程序输出:
1 must greater than 10
this is top exception
b)创建一个自定义的异常类
1 <?php 2 class customerException extends Exception{ 3 public function errorMessage(){ 4 $errorMsg = 'Error on line'.$this->getLine().'in'.$this->getFile().':<b>'.$this->getMessage().'</b> is not a valid E-mail address'; 5 return $errorMsg; 6 } 7 } 8 try{ 9 throw new customerException('error Message'); 10 }catch(customerException $e){ 11 echo $e->errorMessage(); 12 } 13 ?>
c)使用多个catch来返回不同情况下的错误信息
1 <?php 2 $i = 15; 3 try{ 4 if($i>0){ 5 throw new customerException('>0'); 6 } 7 if($i<-10){ 8 throw new Exception('<-10'); 9 } 10 }catch(Exception $e){ 11 echo $e->getMessage(); 12 }catch(customerException $e){ 13 echo $e->errorMessage(); 14 } 15 ?>