search
HomeBackend DevelopmentPHP TutorialPHP error handling and PHP exception handling mechanism_PHP tutorial

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>"; 
?>

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 )
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)
{ //...}

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;
    }
}
?>

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();  


}

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

<?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>";

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/742411.htmlTechArticlephp错误处理 当我们开发程序时,有时候程序出现了问题,我们就可以用以下几种办法找出错误。 开发阶段:开发时输出所有的错误报告,...
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)