php5和php7的异常处理机制 ----thinkphp5 异常处理的分析
1.php异常和错误
在其他语言中,异常和错误是有区别的,但是PHP,遇见自身错误时,会触发一个错误,而不是跑出异常。并且,php大部分情况,都会触发错误,终止程序执行,在php5中,try catch是没有办法处理错误的。
php7是可以捕获错误的;
1.1 php5 错误异常
// 1.异常处理
try{
throw new Exception("Error Processing Request", 1);
}catch ( Exception $e){
echo $e->getCode().'<br/>';
echo $e->getMessage().'<br/>';
echo $e->getLine().'<br/>';
echo $e->getFile().'<br/>';
} 返回: 1
Error Processing Request
158
E:\phpwebenv\PHPTutorial\WWW\test\index.php // 2.结果php错误处理机制
function MyErrorHandler($error,$errstr,$errfile,$errline){
echo '<b> Custom error:</b>'.$error.':'.$errstr.'<br/>';
echo "Error on line $errline in ".$errfile;
}
set_error_handler('MyErrorHandler',E_ALL|E_STRICT);
try{
// throw new Exception("Error Processing Request", 4);
trigger_error('error_msg');
}catch ( Exception $e){
echo $e->getCode().'<br/>';
echo $e->getMessage().'<br/>';
echo $e->getLine().'<br/>';
echo $e->getFile().'<br/>';
} 结果:
Custom error:1024:error_msg
Error on line 164 in E:\phpwebenv\PHPTutorial\WWW\test\index.php //3. 处理致命错误:脚本结束后执行
function shutdown_function(){
$e = error_get_last();
echo '<pre/>';
var_dump($e);
}
register_shutdown_function('shutdown_function');
try{
// throw new Exception("Error Processing Request", 4);
// trigger_error('error_msg');
fun();
}catch ( Exception $e){
echo $e->getCode().'<br/>';
echo $e->getMessage().'<br/>';
echo $e->getLine().'<br/>';
echo $e->getFile().'<br/>';
} 结果: Fatal error: Uncaught Error: Call to undefined function fun() in E:\phpwebenv\PHPTutorial\WWW\
test\index.php:172 Stack trace: #0 {main} thrown in E:\phpwebenv\PHPTutorial\WWW\test\index.php on line 172
array(4) {
["type"]=>
int(1)
["message"]=>
string(131) "Uncaught Error: Call to undefined function fun() in E:\phpwebenv\PHPTutorial\WWW\test\index.php:172
Stack trace:
#0 {main}
thrown"
["file"]=>
string(43) "E:\phpwebenv\PHPTutorial\WWW\test\index.php"
["line"]=>
int(172)
}
以上方法可以看出,php没有捕获到异常,只能依赖set_error_handler()和register_shutdown_function();来处理,set_error_handler只能接受
异常和非致命的错误。register_shutdown_function():主要针对die()或致命错误,即程序终结后执行;所以php5没有很好的异常处理机制。
1.2 php7的异常处理
// 处理致命错误:脚本结束后执行
function shutdown_function(){
$e = error_get_last();
echo '<pre>';
var_dump($e);
}
register_shutdown_function('shutdown_function');
// 结果php错误处理机制
function MyErrorHandler($error,$errstr,$errfile,$errline){
echo '<b> Custom error:</b>'.$error.':'.$errstr.'<br/>';
echo "Error on line $errline in ".$errfile;
}
set_error_handler('MyErrorHandler',E_ALL|E_STRICT);
try{
// throw new Exception("Error Processing Request", 4);
// trigger_error('error_msg');
fun();
}catch ( Error $e){
echo $e->getCode().'<br/>';
echo $e->getMessage().'<br/>';
echo $e->getLine().'<br/>';
echo $e->getFile().'<br/>';
}
结果:
0
Call to undefined function fun()
172
E:\phpwebenv\PHPTutorial\WWW\test\index.php
NULL
register_shutdown_function();没有捕获到异常
// 2. 如果不用try catch 捕获 function exception_handler( Throwable $e){ echo 'catch Error:'.$e->getCode().':'.$e->getMessage().'<br/>'; } set_exception_handler('exception_handler'); fun();
总结: Throwable 是Error 和 Exception 的基类,在php7中,如果既想捕获异常有需要捕获错误
try{
fun();
}catch ( Throwable $e){
echo $e->getCode().'<br/>';
echo $e->getMessage().'<br/>';
echo $e->getLine().'<br/>';
echo $e->getFile().'<br/>';
}
3. thinkphp5框架的错误处理:
在异常错误处理类:Error有这个处理
// 注册错误和异常处理机制
\think\Error::register();
/**
* 注册异常处理
* @return void
*/
public static function register()
{
error_reporting(E_ALL);
set_error_handler([__CLASS__, 'appError']);
set_exception_handler([__CLASS__, 'appException']);
register_shutdown_function([__CLASS__, 'appShutdown']);
}
当程序出现错误时,会执行这些异常、错误的函数;
链接数据库后,处理异常的是:
/**
* 连接数据库方法
* @access public
* @param array $config 连接参数
* @param integer $linkNum 连接序号
* @param array|bool $autoConnection 是否自动连接主数据库(用于分布式)
* @return PDO
* @throws Exception
*/
public function connect(array $config = [], $linkNum = 0, $autoConnection = false)
{
if (!isset($this->links[$linkNum])) {
if (!$config) {
$config = $this->config;
} else {
$config = array_merge($this->config, $config);
}
// 连接参数
if (isset($config['params']) && is_array($config['params'])) {
$params = $config['params'] + $this->params;
} else {
$params = $this->params;
}
// 记录当前字段属性大小写设置
$this->attrCase = $params[PDO::ATTR_CASE]; // 数据返回类型
if (isset($config['result_type'])) {
$this->fetchType = $config['result_type'];
}
try {
if (empty($config['dsn'])) {
$config['dsn'] = $this->parseDsn($config);
}
if ($config['debug']) {
$startTime = microtime(true);
}
$this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params);
if ($config['debug']) {
// 记录数据库连接信息
Log::record('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn'], 'sql');
}
} catch (\PDOException $e) {
if ($autoConnection) {
Log::record($e->getMessage(), 'error');
return $this->connect($autoConnection, $linkNum);
} else {
throw $e;
}
}
}
return $this->links[$linkNum];
} 当数据库链接失败后,可以重新链接或者直接抛出异常;
/**
* 析构方法
* @access public
*/
public function __destruct()
{
// 释放查询
if ($this->PDOStatement) {
$this->free();
}
// 关闭连接
$this->close();
}
当执行sql失败后,调用析构方法,关闭数据库链接;
4. php发生错误时,资源释放
php是解释性脚本,每个php页面都是一个独立的执行程序,不管用什么方式只要执行完了(包括die(),exit(),致命错误终止程序),都会把结果返回给服务器,都会关闭。程序都关闭了,资源当然会被释放; unset();当多个变量名或者对象名指向一块存储地址时,unset()函数的作用仅仅是销毁变量名和存储地址的指向而已,当仅有一个变量名或者对象名,unset销毁的是指定的存储地址上的内容; 析构方法:当实例化的对象,没有其他变量或对象名指向时,就会执行此方法;或者是在脚本结束后,释放对象资源时,执行此方法;
参考资料:http://blog.csdn.net/zhang197093/article/details/75094816
php5和php7的异常处理机制 ----thinkphp5 异常处理的分析的更多相关文章
- Java基础-异常处理机制 及异常处理的五个关键字:try/catch/finally/throw /throws
笔记: /** 异常处理机制: 抓抛模型 * 1."抛", 一旦抛出,程序终止! printStackTrace()显示异常路径! * 2."抓", 抓住异常 ...
- C语言中的异常处理机制
#define try if(!setjmp(Jump_Buffer)) 返回try现场后重新执行判断,所以有两次执行. http://blog.csdn.net/tian_dao_chou_qin/ ...
- JAVA学习之 异常处理机制
今天就来说说java的异常处理机制,异常处理不是第一接触,尤其是写过非常多c#的代码,基本都会写到异常处理的代码,事实上c#的异常处理与java的异常处理基本都是一样的,仅仅是在一些细节上不是非常一样 ...
- java异常处理机制详解
java异常处理机制详解 程序很难做到完美,不免有各种各样的异常.比如程序本身有bug,比如程序打印时打印机没有纸了,比如内存不足.为了解决这些异常,我们需要知道异常发生的原因.对于一些常见的异常,我 ...
- 06_Python异常处理机制
1.异常概述 1.什么是错误: 错误是指有逻辑或语法等导致一个程序无法正常执行的问题 2.什么是异常: 异常时程序出错时标识的一种状态,程序不会向下执行而转去调用此函数的地方等待处理错误并恢复 ...
- ThinkPHP5.0源码学习之注册错误和异常处理机制
在base.php文件中,用一句代码\think\Error::register();实现错误和异常处理机制的注册. // 注册错误和异常处理机制 \think\Error::register(); ...
- php错误处理和php异常处理机制
php错误处理 当我们开发程序时,有时候程序出现了问题,我们就可以用以下几种办法找出错误. 开发阶段:开发时输出所有的错误报告,有利于我们进行程序调试 运行阶段:我们不要让程序输出任何一种错误报 ...
- PHP 注册错误和异常处理机制
注册错误和异常处理机制有三个PHP函数需要学习 1. register_shutdown_function('Bootstrap\Library\Frame::fatalError'); 2. set ...
- Java异常处理机制 try-catch-finally 剖析
Java拥有着强大的异常处理机制,最近初步学习了下,感觉内容还是挺多的,特此来将自己的理解写出来与大家分享. 一. 在Java代码code中,由于使用Myeclipse IDE,可以自动提醒用户哪里有 ...
随机推荐
- SPOJ1825/FTOUR2:Free tour II——包看得懂/看不懂题解
http://www.spoj.com/problems/FTOUR2/en/ 题目大意:给一棵黑白染色的树,求边权和最大且经过黑点不超过K的路径. ———————————————————— 前排膜拜 ...
- Mac安装mysqldb
一. 安装mysql (一)下载地址 https://pan.baidu.com/s/1slw50LZ 安装成功后,在系统偏好设置里有MySQL图标,可以启动或关闭MySQL 二. Mysql roo ...
- BZOJ1022 [SHOI2008]小约翰的游戏John 【博弈论】
1022: [SHOI2008]小约翰的游戏John Time Limit: 1 Sec Memory Limit: 162 MB Submit: 3014 Solved: 1914 [Submi ...
- 征战jQuery
一:jQuery的用途 1>.访问 和 操作 DOM元素 2>.控制 页面样式 3>.对页面事件的处理 4>.方便的使用jQuery插件 5>.与Ajax技术的完美结合 ...
- 【简单算法】40.Fizz Buzz
题目: 写一个程序,输出从 到 n 数字的字符串表示. . 如果 n 是3的倍数,输出“Fizz”: . 如果 n 是5的倍数,输出“Buzz”: .如果 n 同时是3和5的倍数,输出 “FizzBu ...
- MySQL5.7 添加、删除用户与授权
mysql -uroot -proot 例子: 创建用户mysql> CREATE USER 'xiaoyaoji'@'%' IDENTIFIED BY 'xiaoyaoji';Query OK ...
- 关于AVPlayerItem对象的属性duration返回播放总时长的坑
最近在使用AVPlayer播放网络流媒体,发现一个坑: 就是playerItem.duration有可能不返回该网络多媒体资源的播放总时间长度,而是返回了一个奇怪的数据:nan, 因为我通过CMTim ...
- Codeforces Round #340 (Div. 2)B
B. Chocolate time limit per test 1 second memory limit per test 256 megabytes input standard input o ...
- ASP.NET基础学习(暴力破解密码)
首先写出一段登陆程序: //ashx端 <%@ WebHandler Language="C#" Class="AddCalation" %> us ...
- DOM基本代码一
dom学习基本代码第一部分 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> < ...