Home  >  Article  >  Backend Development  >  Basic tutorial for getting started with PHP - PHP error handling

Basic tutorial for getting started with PHP - PHP error handling

WBOY
WBOYOriginal
2016-07-25 09:00:151003browse
This section introduces PHP error handling to you. In any programming language, error capture and processing are very important. It is recommended that you have a firm grasp of it.

In this content, we use 2 examples to show you the usage of PHP error handling. Example 1,

<?php    
    //打开一个文件 未做任何处理
    //$fp =fopen("aa.txt","r");
    //echo "OK";

    //处理:判断文件是否存在 file_exists
    //by bbs.it-home.org
/*
    if(!file_exists("aa.txt")){
        echo "文件不存在";
        //不存在就退出
        exit();  //退出后,下面面的代码就不执行了
    }else{
        $fp =fopen("aa.txt","r");
        //...操作完之后 关闭
        fclose($fp);
    }
    echo "OK";
*/
    //PHP处理错误的3种方法
    //第一种:使用简单的die语句

/*    if(!file_exists("aa.txt")){    
        die("文件不存在。。。"); //不存在就直接退出
    }else{
        $fp =fopen("aa.txt","r");
        //...操作完之后 关闭
        fclose($fp);
    }

    echo "OK";
*/
    //更简单的方式
    file_exists("aa.txt") or die("文件不存在");
?>

Example 2,

<?php
    //第二种:错误处理器 错误级别 处理错误方式
    /*
    使用error_function(error_level,error_message,
    error_file,error_line,error_context)
    该函数必须有能力处理至少两个参数 (error level 和 error message),
    但是可以接受最多五个参数(可选的:file, line-number 以及 error context):
    */

    //改写set_error_handler方法
    //如果出现 E_WARNING 这个错误就调用my_error 处理方法
    set_error_handler("my_error",E_WARNING);
    set_error_handler("my_error2",E_USER_ERROR);
    //设置中国对应的时区
    date_default_timezone_set('PRC');
    
    function my_error($errno,$errmes){
        
        echo "<font size='5' color='red' >$errno</font>"; //输出错误报告级别
        echo "错误信息是:".$errmes;
        exit();
    }

    function my_error2($errno,$errmes){
        
        //echo "错误信息是:".$errno,$errmes;
        //exit();
        //把错误信息输入到文本中保存已备查看 使用到error_log()函数
        $message ="错误信息是:".$errno." ".$errmes;
        error_log(date("Y-m-d G:i:s")."---".$message."\r\n",3,"myerror.txt"); // \r\n 表示换行
    }

    //打开一个文件 未做任何处理

    //$fp =fopen("aa.txt","r");
    //echo "OK";

    //使用自定义错误 要添加触发器 这个trigger_error()函数来指定调用自定义的错误
    $age=200;
    if($age>150){
        //echo "年龄过大";
        //调用触发器 同时指定错误级别 这里需要查看帮助文档
        trigger_error("不好了出大问题了",E_USER_ERROR);
        //exit();
    }
?>

Thank you for paying attention to the PHP introductory tutorials. This series of PHP basic tutorials will help PHP newbies quickly master the PHP programming language. Programmer's Home will continue to launch PHP-related tutorials for everyone, and I wish you all the best in your learning and progress!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn