PHP error handling and PHP exception handling mechanism_PHP tutorial

WBOY
Release: 2016-07-13 10:35:46
Original
889 people have browsed it

php error handling

When we develop a program, sometimes there is a problem with the program. We can use the following methods to find the error.

Development stage: Output all error reports during development, which is helpful for us to debug the program
Running phase: We do not want the program to output any kind of error report (cannot be seen by users (including those who are technical and not technical))

Write error report to log
1. Specify error reporting error_reporting = E_LL
2. Turn off error output display_errors = Off
3. Turn on the error log function log_errors = On

1. By default, if the error log location is not specified, it will be written to the log of the WEB server by default
2. Specify a file name (writable)
for the error_log option 3. Write to the operating system log error_log=syslog

Code example below

<?php
//	error_reporting(E_ALL);
///	ini_set("display_errors", "off");
//	ini_set("error_log", "syslog");
//	ini_set("MAX_FILEUPLOAD", 200000000);
//	echo ini_get("upload_max_filesize");
//	error_log("this is a error message!!!!");
	getType($var);   //注意
	getType();  //警告
	getTye();  //错误  会终止程序运行
	echo "###########################<br>"; 
?>
Copy after login

Of course, php also provides the function error_get_last() to obtain error information

Function definition and usage

The error_get_last() function gets the last error that occurred. This function returns the last errors that occurred as an array. The returned array contains 4 keys and values: [type] - error type [message] - error message [file] - the file where the error occurred [line] - The line where the error occurred

Small example:

<?php echo $test; print_r(error_get_last()); ?>输出:
Array ( [type] => 8 [message] => Undefined variable: test [file] => D:\www\test.php [line] => 2 )
Copy after login
So this is very convenient for us. . . Is this helpful when debugging programs and troubleshooting errors?

These error reporting levels are different types of errors that error handlers are designed to handle:

value Constant Description
2 E_WARNING Nonfatal run-time error. Do not pause script execution.
8 E_NOTICE
常量 描述
2 E_WARNING 非致命的 run-time 错误。不暂停脚本执行。
8 E_NOTICE

Run-time 通知。

脚本发现可能有错误发生,但也可能在脚本正常运行时发生。

256 E_USER_ERROR 致命的用户生成的错误。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_ERROR。
512 E_USER_WARNING 非致命的用户生成的警告。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_WARNING。
1024 E_USER_NOTICE 用户生成的通知。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_NOTICE。
4096 E_RECOVERABLE_ERROR 可捕获的致命错误。类似 E_ERROR,但可被用户定义的处理程序捕获。(参见 set_error_handler())
8191 E_ALL

所有错误和警告,除级别 E_STRICT 以外。

(在 PHP 6.0,E_STRICT 是 E_ALL 的一部分)

Run-time notification. <🎜> <🎜>Script discovery errors may occur, but may also occur while the script is running normally. <🎜>
256 E_USER_ERROR Fatal user-generated error. This is similar to E_ERROR set by the programmer using the PHP function trigger_error().
512 E_USER_WARNING Non-fatal user-generated warning. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error().
1024 E_USER_NOTICE User-generated notifications. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error().
4096 E_RECOVERABLE_ERROR Catchable fatal error. Like E_ERROR, but can be caught by a user-defined handler. (see set_error_handler())
8191 E_ALL <🎜>All errors and warnings except level E_STRICT. <🎜> <🎜> (In PHP 6.0, E_STRICT is part of E_ALL) <🎜>

php异常处理机制

定义:

异常处理: 意外,是在程序运行过程中发生的意料这外的事,使用异常改变脚本正常流程

语法格式:

try
{ //...}
catch(Exception $e)
{ //...}
Copy after login

PHP中try{}catch{}是异常处理.

将要执行的代码放入TRY块中,如果这些代码执行过程中某一条语句发生异常,则程序直接跳转到CATCH块中,由$e收集错误信息和显示.

PHP中try{}catch{}语句

为了进一步处理异常,我们需要使用PHP中try{}catch{}----包括Try语句和至少一个的catch语句。任何调用 可能抛出异常的方法的代码都应该使用try语句。Catch语句用来处理可能抛出的异常。

例子:

我写一段代码:

自己定义一个异常类
作用:就是写一个或多个方法解决当发生这个异常时的处理方式
1. 自己定义异常类,必须是Exception(内置类)的子类, 可以查看PHP手册里面Exception(内置类)的使用方法
2. Exception类中的只有构造方法和toString()可以重写, 其它都final

<?php
class OpenFileException extends Exception {    //继承PHP的内置类

    function __construct($message = null, $code = 0){
        parent::__construct($message, $code);

        echo "wwwwwwwwwwwwwww<br>";
    }
    function open(){
        touch("tmp.txt");

        $file=fopen("tmp.txt", "r");

        return $file;
    }
}
?>
Copy after login

1. 如果try中代码没有问题,则将try中代码执行完后就到catch后执行
2. 如果try中代码有异常发生,则抛出一个异常对象(使用throw),抛出给了catch中的参数, 则在try中代码就不会再继续执行下去 直接跳转到catch中去执行, catch中执行完成, 再继续向下执行
注意: 提示发生了什么异常,这不是主要我们要做事,需要在catch中解决这个异常, 如果解决不了,则出去给用户在下面代码中,如果我没有这个TMP.TXT文件的话,就会抛出异常了。

如果有异常,我们调用OPEN方法就可以解决这个异常了。

<?php

try{

 $file=fopen("tmp.txt", "r");                                                           //  尝试读取这个文件
  if(!$file)
            throw new OpenFileException("文件打开失败");       //如果文件不存在则抛出异常
  
}catch(OpenFileException $e){  //$e =new Exception();
    
    echo $e->getMessage()."<br>";                                        //getMessage() 是PHP里面内置的方法,可以直接调用

    $file=$e->open();  


}
Copy after login

下面将代码进行整理以及多个异常处理方法:

<?php
/* 
 *   异常处理: 意外,是在程序运行过程中发生的意料这外的事,使用异常改变脚本正常流程
 *	
 *	PHP5中的一个新的重要特性
 *
 *	if(){
 *
 *	}else{
 *
 *	}
 *
 *	try {
 *
 *	}catch(异常对象){
 *
 *	}
 * 	
 * 		1. 如果try中代码没有问题,则将try中代码执行完后就到catch后执行
 * 		2. 如果try中代码有异常发生,则抛出一个异常对象(使用throw),抛出给了catch中的参数, 则在try中代码就不会再继续执行下去
 *			直接跳转到catch中去执行, catch中执行完成, 再继续向下执行
 *
 *
 *		注意: 提示发生了什么异常,这不是主要我们要做事,需要在catch中解决这个异常, 如果解决不了,则出去给用户
 *
 *	二、自己定义一个异常类
 *
 *		作用:就是写一个或多个方法解决当发生这个异常时的处理方式
 *
 *		1. 自己定义异常类,必须是Exception(内置类)的子类,
 *		2. Exception类中的只有构造方法和toString()可以重写, 其它都final
 *
 *	三、处理多个异常
 *
 *	
 *	自己定义功能类时如果在方法中抛出异常
 *
 *
 */

class OpenFileException extends Exception {

	function __construct($message = null, $code = 0){
		parent::__construct($message, $code);

		echo "wwwwwwwwwwwwwww<br>";
	}
	function open(){
		touch("tmp.txt");

		$file=fopen("tmp.txt", "r");

		return $file;
	}
}


class DemoException extends Exception {
	function pro(){
		echo "处理demo发生的异常<br>";
	}
}

class TestException extends Exception {
	function pro(){
		echo "这里处理test发生的异常<br>";
	}
}

class HelloException extends Exception {

}

class MyClass {
	function openfile(){
		$file=@fopen("tmp.txt", "r");

		if(!$file)
			throw new OpenFileException("文件打开失败");
	}

	function demo($num=0){
		if($num==1)
			throw new DemoException("演示出异常");
	}

	function test($num=0){
		if($num==1)
			throw new TestException("测试出错");
	}

	function fun($num=0){
		if($num==1)
			throw new HelloException("###########");
	}
}

try{
	echo "11111111111111<br>";

	$my=new MyClass();

	$my->openfile();
	$my->demo(0);
	$my->test(0);
	$my->fun(1);
	echo "22222222222222222<br>";
}catch(OpenFileException $e){  //$e =new Exception();
	
	echo $e->getMessage()."<br>";

	$file=$e->open();


}catch(DemoException $e){
	echo $e->getMessage()."<br>";
	$e->pro();
}catch(TestException $e){
	echo $e->getMessage()."<br>";
	$e->pro();
}catch(Exception $e){
	echo $e->getMessage()."<br>";
}

	var_dump($file);
	echo "444444444444444444444<br>";
Copy after login

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/742411.htmlTechArticlephp错误处理 当我们开发程序时,有时候程序出现了问题,我们就可以用以下几种办法找出错误。 开发阶段:开发时输出所有的错误报告,...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!