PHP的异常捕捉与运行特殊处理

 1.php的错误捕获:try{} catch(Exception  $e) { echo  $e->getMessage();}句型格式对于错误的调试和控制帮助是很是大的。 php

 <?php
  class   test  {
   static  public function  atest($val) {
    if($val>1) throw new Exception("Parms greater than 1");
    if($val<1&&$val>0) throw new Exception("error");
     echo  $val;
   }
  }
  try  {
    $val = 0.5;
   test::atest($val);
  }  catch (Exception  $e) {
  exit(json_encode(array("err_code"=>"500","err_msg"=>$e->getMessage())));
  }
?>

优点:主要用来捕获系统级的错误(业务逻辑层面的错误通常不用捕获)这样避免了方法的污染
ps:捕获能够获取到的信息包括getFile() 获取文件 getLine()获取出错的行 getMessage() 获取插入的提示报错信息。框架机制中,通常都须要提供捕获机制
2.若是不用try{}catch(Exception  $e){}句型
PHP里提供了一个set_exception_handler()的简化写法 json

<?php
   function   test1($e) {
  echo   $e->getMessage();
}
set_exception_handler('test1');
throw new Exception("test");
?>

3.另一个错误提示的函数(和set_exception_handler()类似的用法) 框架

<?php
function  test() {
echo  " XPHP notice error";
}
set_error_handler("test");
test
?>

该段代码会报错XPHP notice error
set_error_handler(error_function,error_types)
参数    描述
error_function     必需。规定发生错误时运行的函数。
error_types     可选。规定在哪一个错误报告级别会显示用户定义的错误。默认是 "E_ALL"。
4.另一个经常使用到的框架函数
register_shutdown_function('endRecord');
脚本运行完成后须要记录的动做 函数

<?php
function  endRecord() {
echo   "PHP Script End";
}
register_shutdown_function('endRecord');
?>
相关文章
相关标签/搜索