search

php异常处理机制

Jun 13, 2016 am 11:50 AM
catchexceptionnbspphpquot

php错误处理和php异常处理机制

php错误处理

当我们开发程序时,有时候程序出现了问题,我们就可以用以下几种办法找出错误。

    开发阶段:开发时输出所有的错误报告,有利于我们进行程序调试
     运行阶段:我们不要让程序输出任何一种错误报告(不能让用户看到(包括懂技术, 不懂技术的人))
 
    将错误报告写入日志中
        一、指定错误报告 error_reporting = E_LL
        二、关闭错误输出 display_errors = Off
        三、开启错误日志功能 log_errors = On

        1. 默认如果不指定错误日志位置,则默认写WEB服务器的日志中
         2. 为error_log选项指定 一个文件名(可写)
         3. 写入到操作系统日志中error_log=syslog

以下代码示例

<span style="font-family:SimSun;font-size:14px;"><?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>"; ?></span>

当然php还提供了函数error_get_last()来获得错误信息

函数定义和用法

error_get_last()函数获取最后发生的错误。
该函数以数组的形式返回最后发生的错误。
返回的数组包含 4 个键和值:
[type] - 错误类型
[message] - 错误消息
[file] - 发生错误所在的文件
[line] - 发生错误所在的

小例子:

<span style="font-family:SimSun;font-size:14px;"><?php echo $test; print_r(error_get_last()); ?>输出:Array ( [type] => 8 [message] => Undefined variable: test [file] => D:\www\test.php [line] => 2 )</span>

php5.4以后也提供了PHP预定义变量$php_errormsg

$php_errormsg前一个错误信息

$php_errormsg 变量包含由 PHP 生成的最新错误信息。这个变量只在错误发生的作用域内可用,并且要求track_errors 配置项是开启的(默认是关闭的)。

例子:

<?php @strpos();echo $php_errormsg;?>

会输出:

Wrong parameter count for strpos()

所以这样我们也很方便了。。。这样是不是对调试程序和排查错误的时候很有帮助呢?


这些错误报告级别是错误处理程序旨在处理的错误的不同的类型:

常量 描述
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 的一部分)

php异常处理机制

定义:

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

语法格式:

<span style="font-family:SimSun;font-size:14px;">try{ //...}catch(Exception $e){ //...}</span>

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

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

PHP中try{}catch{}语句

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

例子:

我写一段代码:

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

<span style="font-family:SimSun;font-size:14px;"><?phpclass 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;    }}?></span>

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

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

<span style="font-family:SimSun;font-size:14px;"><?phptry { $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();  }</span>

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

<span style="font-family:SimSun;font-size:14px;"><?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(){		[email protected]("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>";</span>

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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.