php 异常和错误处理机制

WBOY
Release: 2016-06-23 13:24:07
Original
768 people have browsed it

php只有手动抛出异常才能捕获异常

class emailException extends Exception{            //定义魔术方法 ,直接输出对象的信息	public function __toStirng(){		$error = "Code:{$this->getCode()},message:{$this->getMessage()} line:{$this->getLine()},file:{$this->getFile()}";		return $error;	}}function reg($i){	if($i>0){		throw new emailException("错误");	}}try{		reg($i=6);}catch(emailException $e){	echo $e;	echo $e->getMessage();}catch(Exception $e){    $e->getMessage();}//此处需要注意  exception 作为超类应该放到最后捕获//如果提前捕获这个超类,后面的捕获就终止了,而且不提供 针对性的信息处理
Copy after login

运行图

自定义 异常处理函数(只能捕获到异常和非致命的错误,致命的错误还是会挂掉)

function  customError($errno,$errstr,$errfile,$errline){		echo "<b>错误代码</b>[${error}]${errstr}"."</br>";	echo "错误所在代码行:{$errline}文件{$errfile}"."</br>";	echo "PHP版本",PHP_VERSION,"(",PHP_OS,")"."</br>";}set_error_handler("customError",E_ALL|E_STRICT); $a = array('o'=>2,4,6,8);echo $a[o];  //错误的代码//set_error_handler()函数会接管php内置的错误处理,//可以在同一个页面使用 restore_error_handler()取消接管
Copy after login

运行图:

简单处理fetal error的错误

class Shutdown{				public function stop(){			if(error_get_last()){				print_r(error_get_last());			}			die('Stop.');		}	}	register_shutdown_function(array(new Shutdown(),'stop')); 	//此函数会在php程序终止或者die时触发一个函数	$a = new a(); //错误代码	echo "致命错误";
Copy after login

运行图:

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!