Skip to content

Latest commit

 

History

History
125 lines (88 loc) · 6.44 KB

Exception.md

File metadata and controls

125 lines (88 loc) · 6.44 KB

Exception

目的:学习笔记,会根据使用经验,持续补充ing

异常基本函数

异常Exception 是所有异常的基类。

异常的子类

我们继承Exception这个基类,创建自己的异常类。

创建不同的异常类,是为了在catch的时候,可以捕捉不同的异常,并根据不同的异常类型做不同的处理。

至于创建自己异常类的标准,可以参考 SPL 提供一系列标准异常

示例代码

    try{
	       echo testParams('ha');
	    }catch (StringException $stringException) {
		   echo "lengthException:".$stringException->getMessage();
	    }catch (lengthException $lengthException) {
		    echo "lengthException:".$lengthException->getMessage();
	  }
	
	function testParams($param) {
    
    		if(!is_string($param)) {
    			throw new StringException("is not string");
    		}
    
    		if(strlen($param) < 5) {
    			throw new LengthException('length is not enough');
    		}
    		return $param;
    	}
    	
    	class LengthException extends Exception
        {
        
        }
        
        class StringException extends Exception
        {
        
        }

错误和异常配置

在开发环境中,我们需要显示所有可能的错误,所以在php.ini中的配置

display_errors = On #String 该选项设置是否将错误信息作为输出的一部分显示到屏幕,或者对用户隐藏而不显示
display_startup_errors = On #boolean 即使 display_errors 设置为开启, PHP 启动过程中的错误信息也不会被显示。强烈建议除了调试目的以外,将 display_startup_errors 设置为关闭。
error_reporting = -1 #boolean 即使 display_errors 设置为开启, PHP 启动过程中的错误信息也不会被显示。强烈建议除了调试目的以外,将 display_startup_errors 设置为关闭。
log_errors = On #boolean 设置是否将脚本运行的错误信息记录到服务器错误日志或者error_log之中。注意,这是与服务器相关的特定配置项。

生产环境中,我们要隐藏错误信息

display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL
log_errors = On

详细信息看手册

SPL 提供一系列标准异常

异常和错误处理函数

  • set_exception_handler
  • restore_exception_handler

异常和错误的区别?

异常按理说是应用程序上的逻辑异常,可以通过合理的手段解决;

错误一般指语法错误、逻辑错误等

持续补充ing

参考: