php异常处理

合集下载

php知识点

php知识点

php知识点一、PHP基础知识PHP是一种脚本语言,常用于Web开发,但也可以用于命令行界面(CLI)脚本编写。

PHP是一种开源的、免费的、跨平台的语言,可以在各种操作系统上运行,包括Windows、Linux、Unix等。

PHP的语法类似于C语言,但更加简单易懂,因此学习起来相对较容易。

1. 数据类型PHP支持多种数据类型,包括整型、浮点型、布尔型、字符串型、数组、对象等。

其中,整型和浮点型可以进行算术运算,布尔型只有true和false两个值,字符串型可以使用单引号或双引号来表示,数组是一种用于存储多个值的数据结构,对象是一种面向对象编程的概念。

2. 变量变量是存储值的容器,可以存储各种数据类型的值。

在PHP中,变量必须以$符号开头,后面跟着变量名。

变量名可以包含字母、数字和下划线,但不能以数字开头。

变量的值可以通过赋值语句进行修改。

3. 运算符PHP支持多种运算符,包括算术运算符、比较运算符、逻辑运算符等。

算术运算符用于数学计算,比较运算符用于比较两个值的大小关系,逻辑运算符用于组合多个条件,形成复杂的逻辑表达式。

4. 控制流程语句PHP支持多种控制流程语句,包括if语句、switch语句、while语句、for语句等。

这些语句可以根据不同的条件执行不同的代码块,实现程序的控制流程。

二、PHP高级知识PHP不仅仅是一种简单易学的语言,还有很多高级的特性和技术,可以用于构建复杂的Web应用程序。

以下是一些PHP高级知识点:1. 面向对象编程PHP支持面向对象编程,可以使用类和对象来组织代码。

面向对象编程具有很多优点,包括代码复用、封装性、可维护性等。

2. 异常处理PHP提供了异常处理机制,可以在程序发生异常时进行捕获和处理。

异常处理可以避免程序崩溃,提高代码的健壮性。

3. 文件操作PHP可以读写文件,操作文件系统。

通过文件操作,可以实现数据的持久化存储和读取。

4. 数据库操作PHP可以连接和操作各种数据库,包括MySQL、Oracle、SQL Server等。

什么是异常处理异常处理的特点

什么是异常处理异常处理的特点

什么是异常处理异常处理的特点异常处理是编程语言或计算机硬件里的一种机制,用于处理软件或信息系统中出现的异常状况,那么你对异常处理了解多少呢?以下是由店铺整理关于什么是异常处理的内容,希望大家喜欢!异常处理的概述各种编程语言在处理异常方面具有非常显著的不同点(错误检测与异常处理区别在于:错误检测是在正常的程序流中,处理不可预见问题的代码,例如一个调用操作未能成功结束)。

某些编程语言有这样的函数:当输入存在非法数据时不能被安全地调用,或者返回值不能与异常进行有效的区别。

例如,C语言中的atoi函数(ASCII串到整数的转换)在输入非法时可以返回0。

在这种情况下编程者需要另外进行错误检测(可能通过某些辅助全局变量如C的errno),或进行输入检验(如通过正则表达式),或者共同使用这两种方法。

通过异常处理,我们可以对用户在程序中的非法输入进行控制和提示,以防程序崩溃。

从进程的视角,硬件中断相当于可恢复异常,虽然中断一般与程序流本身无关。

从子程序编程者的视角,异常是很有用的一种机制,用于通知外界该子程序不能正常执行。

如输入的数据无效(例如除数是0),或所需资源不可用(例如文件丢失)。

如果系统没有异常机制,则编程者需要用返回值来标示发生了哪些错误。

异常处理的特点1.在应用程序遇到异常情况(如被零除情况或内存不足警告)时,就会产生异常。

2.发生异常时,控制流立即跳转到关联的异常处理程序(如果存在)。

3.如果给定异常没有异常处理程序,则程序将停止执行,并显示一条错误信息。

4.可能导致异常的操作通过 try 关键字来执行。

5.异常处理程序是在异常发生时执行的代码块。

在C# 中,catch关键字用于定义异常处理程序。

6.程序可以使用 throw 关键字显式地引发异常。

7.异常对象包含有关错误的详细信息,其中包括调用堆栈的状态以及有关错误的文本说明。

8.即使引发了异常,finally 块中的代码也会执行,从而使程序可以释放资源。

try catch用法 php

try catch用法 php

标题:深入剖析PHP中try catch的使用方法在PHP编程中,try catch语句被广泛运用于错误处理和异常捕获。

本文将深入探讨PHP中try catch的用法,并结合具体示例进行详细说明。

1. 简介在PHP编程中,try catch语句被用来捕获可能出现的异常,从而让程序在出错时能够优雅地处理错误情况。

它的语法结构如下:```try {// 可能抛出异常的代码} catch (Exception $e) {// 异常处理代码}```2. try块try块中包含可能会抛出异常的代码。

在这个块中,我们可以放置一些疑似会导致程序出错的代码,同时在catch块中正确处理异常并给出相应的错误提示。

3. catch块catch块用来捕获try块中抛出的异常,然后执行相应的异常处理代码。

在catch块中,我们可以根据具体的异常类型来进行不同的处理,比如记录错误日志、给用户友好的错误提示等。

4. finally块除了try和catch块之外,try catch语句还可以包含一个finally块。

不论是否抛出异常,finally块中的代码都会被执行,常用于资源的释放等清理工作。

5. try catch的嵌套使用try catch语句可以嵌套使用,这样可以更细致地捕获和处理异常。

在嵌套的try catch语句中,我们可以根据不同的层次和逻辑来处理异常,增加程序的健壮性和容错性。

6. 个人观点在实际的PHP开发中,try catch语句是非常重要的异常处理工具。

合理地使用try catch语句,可以帮助我们更好地排查和解决错误,使程序更加健壮和稳定。

在编写代码时,我们应该养成良好的习惯,及时捕获和处理可能出现的异常,以免出现严重的程序崩溃或安全问题。

要注意避免滥用try catch语句,要在适当的场景下使用它,避免过多地隐藏错误和异常。

结语通过本文的介绍,我们对PHP中try catch语句的使用方法有了更加深入的了解。

PHP应用程序的错误处理方法

PHP应用程序的错误处理方法

PHP应用程序的错误处理方法1. 引言PHP是一种开发网站的编程语言,广泛用于构建应用程序和动态网站。

在开发任何应用程序时,出现错误是不可避免的。

因此,了解PHP应用程序的错误处理方法对于开发人员至关重要。

2. 错误处理方法在PHP中,可以使用以下方法处理应用程序中的错误。

2.1. 错误报告默认情况下,PHP会向客户端显示错误报告。

这些报告可以帮助开发人员识别和修复错误,但对于终端用户来说可能过于技术性。

可以使用以下方法关闭错误报告。

在PHP代码中,使用以下指令关闭错误报告:error_reporting(0);在PHP配置文件中,将error_reporting设置为0:error_reporting=02.2. 错误日志错误日志是记录PHP应用程序中的错误的文件。

通过错误日志,开发人员可以查看应用程序中的错误信息并进行排除。

在PHP代码中,可以使用以下指令将错误日志写入文件:ini_set('error_log', '/path/to/error.log');在PHP配置文件中,可以设置以下参数将错误日志写入文件:error_log = /path/to/error.log2.3. 异常处理异常是在运行时发生的错误。

使用异常处理可以在异常发生时执行特定操作。

在PHP中,可以使用以下语法抛出异常:throw new Exception('Error message');可以使用try-catch语句捕获和处理异常:try {// 代码块} catch (Exception $e) {echo 'Caught exception: ', $e->getMessage(), "\n";}2.4. 自定义错误处理方法可以使用set_error_handler()函数自定义PHP应用程序的错误处理程序。

通过自定义错误处理程序,可以在出现错误时采取特定操作。

thinkphp6:自定义异常处理使统一返回json数据(thinkphp6.0.5php。。。

thinkphp6:自定义异常处理使统一返回json数据(thinkphp6.0.5php。。。

thinkphp6:⾃定义异常处理使统⼀返回json数据(thinkphp6.0.5php。

⼀,创建统⼀返回json格式数据的result类app/business/Result/Result.php<?phpnamespace app\business\Result;class Result {//successstatic public function Success($data) {$rs = ['code'=>0,'msg'=>"success",'data'=>$data,];return json($rs);}//errorstatic public function Error($code,$msg) {$rs = ['code'=>$code,'msg'=>$msg,'data'=>"",];return json($rs);}}说明:刘宏缔的架构森林是⼀个专注架构的博客,地址:对应的源码可以访问这⾥获取:说明:作者:刘宏缔邮箱: 371125307@⼆,测试效果:正常返回数据:1,在controller中调⽤:<?phpnamespace app\adm\controller;use app\BaseController;use app\business\Result\Result;class Index extends BaseController{//hello,demopublic function hello($name = 'ThinkPHP6'){//return 'hello,' . $name;$data = array("name"=>$name,"str"=>"hello,".$name."!");return Result::Success($data);}}2,测试,访问:http://127.0.0.1:81/adm/index/hello?name=laoliu返回:三,创建⾃定义的异常类,主要处理404/500等情况app/business/Exception/MyException.php<?phpnamespace app\business\Exception;use think\exception\Handle;use think\exception\HttpException;use think\exception\ValidateException;use think\Response;use Throwable;use ErrorException;use Exception;use InvalidArgumentException;use ParseError;//use PDOException;use think\db\exception\DataNotFoundException;use think\db\exception\ModelNotFoundException;use think\exception\ClassNotFoundException;use think\exception\HttpResponseException;use think\exception\RouteNotFoundException;use TypeError;use app\business\Result\Result;class MyException extends Handle{public function render($request, Throwable $e): Response{//如果处于调试模式if (env('app_debug')){//return Result::Error(1,$e->getMessage().$e->getTraceAsString());return parent::render($request, $e);}// 参数验证错误if ($e instanceof ValidateException) {return Result::Error(422,$e->getError());}// 请求404异常 , 不返回错误页⾯if (($e instanceof ClassNotFoundException || $e instanceof RouteNotFoundException) || ($e instanceof HttpException && $e->getStatusCode() == 404)) {return Result::Error(404,'当前请求资源不存在,请稍后再试');}//请求500异常, 不返回错误页⾯//$e instanceof PDOException ||if ($e instanceof Exception || $e instanceof HttpException || $e instanceof InvalidArgumentException || $e instanceof ErrorException || $e instanceof ParseError || $e instanceof TypeError) { $this->reportException($request, $e);return Result::Error(500,'系统异常,请稍后再试');}//其他错误$this->reportException($request, $e);return Result::Error(1,"应⽤发⽣错误");}//记录exception到⽇志private function reportException($request, Throwable $e):void {$errorStr = "url:".$request->host().$request->url()."\n";$errorStr .= "code:".$e->getCode()."\n";$errorStr .= "file:".$e->getFile()."\n";$errorStr .= "line:".$e->getLine()."\n";$errorStr .= "message:".$e->getMessage()."\n";$errorStr .= $e->getTraceAsString();trace($errorStr, 'error');}}四,指定使⽤⾃定义异常类:1,app/provider.php指定'think\exception\Handle'的路径为⾃定义的MyException类的路径<?phpuse app\ExceptionHandle;use app\Request;// 容器Provider定义⽂件return ['think\Request' => Request::class,//'think\exception\Handle' => ExceptionHandle::class,'think\exception\Handle' => '\\app\\business\\Exception\\MyException'];2,在⼀个controller的⽅法中加⼊除0代码,供测试⽤: app/adm/controller/Index.php<?phpnamespace app\adm\controller;use app\BaseController;use app\business\Result\Result;class Index extends BaseController{public function index(){$div = 0;$a = 100 / $div;$data = array("name"=>"liuhongdi","age"=>20);return Result::Success($data);}public function hello($name = 'ThinkPHP6'){//return 'hello,' . $name;$data = array("name"=>$name,"str"=>"hello,".$name."!");return Result::Success($data);}}五,测试效果1,访问⼀个不存在的url,例如:http://127.0.0.1:81/abcdef返回:2,访问包含除0错误的url:http://127.0.0.1:81/adm/返回:六,查看thinkphp的版本liuhongdi@ku:/data/php/mytp$ php think versionv6.0.5七,查看php的版本:liuhongdi@ku:/data/logs/phplogs/tlog/202012$ php --versionPHP 7.4.9 (cli) (built: Oct 26 2020 15:17:14) ( NTS )Copyright (c) The PHP GroupZend Engine v3.4.0, Copyright (c) Zend Technologieswith Zend OPcache v7.4.9, Copyright (c), by Zend Technologies。

零点起飞学PHP之错误处理

零点起飞学PHP之错误处理

7.1.2 环境错误
环境错误通常是指PHP运行的环境和相关服务关联的 问题,例如PHP程序需要使用的相关模块没有被正确 加载、服务器没有启动、数据库配置错误等等。由于 我们使用的是集成开发环境,因此这些问题出现的概 率是比较小的,集成环境的制作者已经替我们做了大 量的工作。但是如果是初次自己搭建一个环境来运行, 通常情况下会非常的吃力。环境错误所涉及的编程语 言之外的知识比较多,因此本书我们不做详细讲解。
2.使用error_reporting() 函数
【示例7-8】演示不使用error_reporting函数设置时候将0作 为除数,未定义的变量作为被除数后的运行结果。 从运行结果我可以看出有一条变量为定义的提示和一条0作 为除数的警告。下面我就通过设置错误报告来使警告不再 提示,代码如下: 01 <?php 02 error_reporting(E_ALL&~E_WARNING); 03 echo '$a/0='.$a/0; 04 ?> 从运行结果可以看到,警告信息已经不再显示,而提示信 息还在显示,这就演示了使用error_reporting函数可以使得 PHP的错误报告非常灵活。
第7章 错误处理
错误在编程的过程中通常是无法避免的。我们在前面 的学习过程中也碰到了多处错误。PHP系统可以帮助 我们就提示以及修正一些错误。我们也可以自己定义 一些抛出和处理错误方法。本章将详细讲解错误发送 的原因和种类以及处理这些错误的方法。
7.1 错误发生的原因
错误发生的原因有多种,他们按照特点可以分为大的 四类,分别是语法错误、环境错误、逻辑错误和运行 时错误。本节就来介绍这些错误。
256
512 1024 2048 4096

错误处理及调试.

错误处理及调试.

6.1 错误处理概述
• 6.1.1 常见的错误类型
在PHP中,错误用于指出语法、环境或编程问题。根据错误出现
在编程过程中的不同环节,大致可以分为四类,具体如下: 1、语法错误 语法错误是指编写的代码不符合PHP的编写规范。语法错误最常 见,也最容易修复,例如,遗漏了一个分号,就会显示错误信息。这 类错误会阻止PHP脚本执行,通常发生在程序开发时,可以通过错误 报告进行修复,再重新6.2.1 显示错误报告
3、die()函数
die()函数可以用来自定义输出错误信息,常用于业务逻辑的错误 显示。 注意:使用函数控制的方式只对当前脚本有效,而配置php.ini文件对 所有脚本都有效。
6.1 错误处理概述
• 6.1.1 常见的错误类型
2、运行错误 运行错误一般不会阻止PHP脚本的执行,但是会阻止脚本做希望 它做的任何事情,例如,在调用header()函数前如果有字符输出, PHP通常会显示一条错误信息。虽然PHP脚本继续执行,但header()
函数并没有执行成功。
3、逻辑错误 逻辑错误是最让人头疼的,不但不会阻止PHP脚本的执行,也不 会显示出错误信息。例如,在if语句中判断两个变量的值是否相等。 如果错把比较运算符“==”写成赋值运算符“=”就是一种逻辑错 误,很难被发现。
显示除E_NOTICE之外的所有级别错误,第1行表示显示错误报告。
6.2 如何处理错误
• 6.2.1 显示错误报告
2、error_reporting()和ini_set()函数 通过PHP语言提供的error_reporting()和ini_set()函数来实现显示错 误报告,代码如下所示: <?php error_reporting(E_ALL & ~E_NOTICE); ini_set('display_errors',1); ?> 上述代码中,ini_set()函数用来设置错误信息是否显示,error_report ing()函数用于设置错误级别。第2行表示显示除E_NOTICE之外的所有级 别错误,第3行表示显示错误信息。

php_错误处理机制

php_错误处理机制

exit(); } ?>
可以看到,通过结合使用 throw 关键字和 try-catch 语句,我们可以避免错误标记“污染”类方法返 回的值。因为“异常”本身就是一种与其它任何对象不同的 PHP 内建的类型,不会产生混淆。 如果抛出了一个异常,try 语句中的脚本将会停止执行,然后马上转向执行 catch 语句中的脚本。 如果异常抛出了却没有被捕捉到,就会产生一个 fatal error。
这里有两个地方的调用可能导致程序出错(__construct()和
getCommandObject())。尽管如此,我们不需要调整我们的客户代码。你可以在 try 语句中增
getErrorStr()、 getError()和 error()等功能相同的函数。
然而,实际开发中要让程序中的所有类都从同一个类中继承而来是很困难的,除非同时使用接口 (interface)否则无法实现一些子类自身特有的功能, 但那已经是 PHP5 的内容。 就像我们将提到的, PHP5 中提供了更好的解决方案。
同时处理多个错误
在目前为止异常处理看起来和我们传统的作法—检验返回的错误标识或对象的值没有什么太大区别。让我 们将 CommandManager 处理地更谨慎, 并在构造函数中检查 command 目录是否存在。 index_php5_2.php
<?php // PHP 5 require_once('cmd_php5/Command.php'); class CommandManager { private $cmdDir = "cmd_php5";
返回 Error flag(错误标记)
脚本层次的错误处理比较粗糙但很有用。尽管如此,我们有时需要更大的灵活性。我们可以使用返回 错误标识的办法来告诉客户代码“错误发生了!”。这将程序是否继续,如何继续的责任交给客户代码来决 定。 这里我们改进了前面的例子来返回一个脚本执行出错的标志(false 是一个常用的不错的选择)。
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

php异常处理Table of Contents扩展(extend)PHP 内置的异常处理类PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block.The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.catchMultiple catch blocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within the try block) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block.When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().finallyIn PHP 5.5 and later, a finally block may also be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.注释Note:Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.TipThe Standard PHP Library (SPL) provides a good number of built-in exceptions.范例Example #3 Throwing an Exception<?phpfunction inverse($x) {if (!$x) {throw new Exception('Division by zero.');}return 1/$x;}try {echo inverse(5) . "\n";echo inverse(0) . "\n";} catch (Exception $e) {echo 'Caught exception: ', $e->getMessage(), "\n"; }// Continue executionecho "Hello World\n";?>以上例程会输出:0.2Caught exception: Division by zero.Hello WorldExample #4 Exception handling with a finally block<?phpfunction inverse($x) {if (!$x) {throw new Exception('Division by zero.');}return 1/$x;}try {echo inverse(5) . "\n";} catch (Exception $e) {echo 'Caught exception: ', $e->getMessage(), "\n"; } finally {echo "First finally.\n";}try {echo inverse(0) . "\n";} catch (Exception $e) {echo 'Caught exception: ', $e->getMessage(), "\n"; } finally {echo "Second finally.\n";}// Continue executionecho "Hello World\n";?>以上例程会输出:0.2First finally.Caught exception: Division by zero.Second finally.Hello WorldExample #5 Nested Exception<?phpclass MyException extends Exception { }class Test {public function testing() {try {try {throw new MyException('foo!');} catch (MyException $e) {// rethrow itthrow $e;}} catch (Exception $e) {var_dump($e->getMessage());}}}$foo = new Test;$foo->testing();?>以上例程会输出:string(4) "foo!"add a note add a noteUser Contributed Notes 26 notesupdown135 zmunoz at gmail dot com ¶6 years agoWhen catching an exception inside a namespace it is important that you escape to the global space:<?phpnamespace SomeNamespace;class SomeClass {function SomeFunction() {try {throw new Exception('Some Error Message');} catch (\Exception $e) {var_dump($e->getMessage());}}}?>updown72 Johan ¶5 years agoCustom error handling on entire pages can avoid half rendered pages for the users:<?phpob_start();try {/*contains all page logicand throws error if needed*/...} catch (Exception $e) {ob_end_clean();displayErrorPage($e->getMessage());}?>updown9 ohcc at 163 dot com ¶9 months agoType declarations will trigger Uncaught TypeError when a different type is passed. And it cannot be caught with the Exception class.<?phpfunction xc(array $a){}try{xc(4);}catch (Exception $e){ // failed to catch itecho $e->getMessage();}?>You should use TypeError instead for PHP 7+,<?phpfunction xc(array $a){}try{xc(4);}catch (TypeError $e){echo $e->getMessage();}?>In php version prior to 7.0, you should translate Catchable fatal errors to an exception and then catch it.<?phpfunction exceptionErrorHandler($errNumber, $errStr, $errFile, $errLine ) {throw new ErrorException($errStr, 0, $errNumber, $errFile, $errLine);}set_error_handler('exceptionErrorHandler');function s(array $a){}try{s(4);}catch (Exception $e){echo $e->getMessage();}?>updown49 ask at nilpo dot com ¶7 years agoIf you intend on creating a lot of custom exceptions, you may find this code useful. I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes. It also properly pushes all information back to the parent constructor ensuring that nothing is lost. This allows you to quickly create new exceptions on the fly. It also overrides the default __toString method with a more thorough one.<?phpinterface IException{/* Protected methods inherited from Exception class */public function getMessage(); // Exception messagepublic function getCode(); // User-defined Exception code public function getFile(); // Source filenamepublic function getLine(); // Source linepublic function getTrace(); // An array of the backtrace()public function getTraceAsString(); // Formated string of trace/* Overrideable methods inherited from Exception class */public function __toString(); // formated string for displaypublic function __construct($message = null, $code = 0);}abstract class CustomException extends Exception implements IException{protected $message = 'Unknown exception'; // Exception messageprivate $string; // Unknownprotected $code = 0; // User-defined exception code protected $file; // Source filename of exception protected $line; // Source line of exceptionprivate $trace; // Unknownpublic function __construct($message = null, $code = 0){if (!$message) {throw new $this('Unknown '. get_class($this));}parent::__construct($message, $code);}public function __toString(){return get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n". "{$this->getTraceAsString()}";}}?>Now you can create new exceptions in one line:<?phpclass TestException extends CustomException {}?>Here's a test that shows that all information is properly preserved throughout the backtrace.<?phpfunction exceptionTest(){try {throw new TestException();}catch (TestException $e) {echo "Caught TestException ('{$e->getMessage()}')\n{$e}\n";}catch (Exception $e) {echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n";}}echo '<pre>' . exceptionTest() . '</pre>';?>Here's a sample output:Caught TestException ('Unknown TestException')TestException 'Unknown TestException' in C:\xampp\htdocs\CustomException\CustomException.php(31)#0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException->__construct() #1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest()#2 {main}updown7 hweidmann at online dot de ¶11 months agocatch doesn't check for the existence of the Exception class, so avoid typo.<?phpclass MyException extends Exception{...}try{throw new MyException(...);}catch (MuException $e) // <--- typo{...}?>You WON'T getFatal error: Class MuException could not be loaded ...You WILL getFatal error: Uncaught exception 'MyException' ...updown23 php at marcuspope dot com ¶2 years agoUsing a return statement inside a finally block will override any other return statement or thrown exception from the try block and all defined catch blocks. Code execution in the parent stack will continue as if the exception was never thrown.Frankly this is a good design decision because it means I can optionally dismiss all thrown exceptions from 1 or more catch blocks in one place, without having to nest my whole try block inside an additional (and otherwise needless) try/catch block.This is the same behavior as Java, whereas C# throws a compile time error when a return statement exists inside a finally block. So I figured it was worth pointing out to PHP devs who may not have any exposure to finally blocks or how other languages do it.<?phpfunction asdf(){try {throw new Exception('error');}catch(Exception $e) {echo "An error occurred";throw $e;}finally {//This overrides the exception as if it were never thrownreturn "\nException erased";}}try {echo asdf();}catch(Exception $e) {echo "\nResult: " . $e->getMessage();}?>The output from above will look like this:An error occurredException erasedWithout the return statement in the finally block it would look like this:An error occurredResult: errorupdown16 jazfresh at ¶10 years agoSometimes you want a single catch() to catch multiple types of Exception. In a language like Python, you can specify multiple types in a catch(), but in PHP you can only specify one. This can be annoying when you want handle many different Exceptions with the same catch() block.However, you can replicate the functionality somewhat, because catch(<classname> $var) will match the given <classname> *or any of it's sub-classes*.For example:<?phpclass DisplayException extends Exception {};class FileException extends Exception {};class AccessControl extends FileException {}; // Sub-class of FileExceptionclass IOError extends FileException {}; // Sub-class of FileExceptiontry {if(!is_readable($somefile))throw new IOError("File is not readable!");if(!user_has_access_to_file($someuser, $somefile))throw new AccessControl("Permission denied!");if(!display_file ($somefile))throw new DisplayException("Couldn't display file!");} catch (FileException $e) {// This block will catch FileException, AccessControl or IOError exceptions, but not Exceptionsor DisplayExceptions.echo "File error: ".$e->getMessage();exit(1);}?>Corollary: If you want to catch *any* exception, no matter what the type, just use "catch(Exception $var)", because all exceptions are sub-classes of the built-in Exception.updown10 jim at anderos dot com ¶2 years agoIf you are using a namespace, you must indicate the global namespace when using Exceptions. <?phpnamespace alpha;function foo(){throw new \Exception("Something is wrong!");// throw new Exception(""); will fail}try {foo();} catch( \Exception $e ) {// catch( Exception $e ) will give no warning, but will not catch Exceptionecho "ERROR: $e";}?>updown12 Edu ¶3 years agoThe "finally" block can change the exception that has been throw by the catch block.<?phptry{try {throw new \Exception("Hello");} catch(\Exception $e) {echo $e->getMessage()." catch in\n";throw $e;} finally {echo $e->getMessage()." finally \n";throw new \Exception("Bye");}} catch (\Exception $e) {echo $e->getMessage()." catch out\n";}?>The output is:Hello catch inHello finallyBye catch outupdown12 sander at rotorsolutions dot nl ¶3 years agoJust an example why finally blocks are usefull (5.5)<?php//without catchfunction example() {try {//do something that throws an exeption}finally {//this code will be executed even when the exception is executed}}function example2() {try {//open sql connection check user as exampleif(condition) {return false;}}finally {//close the sql connection, this will be executed even if the return is called.}}?>updown8 Shot (Piotr Szotkowski) ¶7 years ago‘Normal execution (when no exception is thrown within the try block, *or when a catch matching the thrown exception’s class is not present*) will continue after that last catch blockdefined in sequence.’‘If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …”message, unless a handler has been defined with set_exception_handler().’These two sentences seem a bit contradicting about what happens ‘when a catch matching the thrown exception’s class is not present’(and the second sentence is actually correct).updown5 telefoontoestel at nospam dot org ¶2 years agoWhen using finally keep in mind that when a exit/die statement is used in the catch block it will NOT go through the finally block.<?phptry {echo "try block<br />";throw new Exception("test");} catch (Exception $ex) {echo "catch block<br />";} finally {echo "finally block<br />";}// try block// catch block// finally block?><?phptry {echo "try block<br />";throw new Exception("test");} catch (Exception $ex) {echo "catch block<br />";exit(1);} finally {echo "finally block<br />";}// try block// catch block?>updown1 Mohammad Hossein Darvishanpour ¶4 months ago<?phpfunction Test_Extention($var1){if($var1 == false){throw new Exception('Invalid !');}}//end functiontry{Test_Extention(false);printf("%s","Valid");}catch(Exception $e){printf("%s","Message : " . $e->getMessage());}?>updown4 Simo ¶1 year ago#3 is not a good example. inverse("0a") would not be caught since (bool) "0a" returns true, yet 1/"0a" casts the string to integer zero and attempts to perform the calculation.updown12 michael dot ochs at gmx dot net ¶8 years agoActually it isn't possible to do:<?phpsomeFunction() OR throw new Exception();?>This leads to a T_THROW Syntax Error. If you want to use this kind of exceptions, you can do the following:<?phpfunction throwException($message = null,$code = null) {throw new Exception($message,$code);}someFunction() OR throwException();?>updown5 cyrus+php at boadway dot ca ¶2 years agoThere's some inconsistent behaviour associated with PHP 5.5.3's finally and return statements. If a method returns a variable in a try block (e.g. return $foo;), and finally modifies that variable, the /modified/ value is returned. However, if the try block has a return that has to be evaluated in-line (e.g. return $foo+0;), finally's changes to $foo will /not/ affect the return value.[code]function returnVariable(){$foo = 1;try{return $foo;} finally {$foo++;}}function returnVariablePlusZero(){$foo = 1;try{return $foo + 0;} finally {$foo++;}}$test1 = returnVariable(); // returns 2, not the correct value of 1.$test2 = returnVariablePlusZero(); // returns correct value of 1, but inconsistent with $test1.[/code]It looks like it's trying to be efficient by not allocating additional memory for the return value when it thinks it doesn't have to, but the spec is that finally is run after try is completed execution, and that includes the evaluation of the return expression.One could argue (weakly) that the first method should be the correct result, but at least the two methods should be consistent.updown3 sander at rotorsolutions dot nl ¶3 years agoJust an example why finally blocks are usefull (5.5)<?php//without catchfunction example() {try {//do something that throws an exeption}finally {//this code will be executed even when the exception is executed}}function example2() {try {//open sql connection check user as exampleif(condition) {return false;}}finally {//close the sql connection, this will be executed even if the return is called.}}updown1 ohcc at 163 dot com ¶19 days agoIf a TRY has a FINALLY, a RETURN either in the TRY or a CATCH won't terminate the script. Code in the same block after the RETURN will not be executed, and the RETURN itself will be "copied" to the bottom of the FINALLY block to be executed.a RETURN in the FINALLY block will override value(s) returned from the TRY or a CATCH block.An EXIT or a DIE always terminate the script after themselves.code 1<?phpfunction foo(){$bar = 1;try{throw new Exception('I am Wu Xiancheng.');}catch(Exception $e){return $bar;$bar--; // this line will be ignored}finally{$bar++;}}echo foo(); // 2?>code 2<?phpfunction foo(){$bar = 1;try{throw new Exception('I am Wu Xiancheng.');}catch(Exception $e){return $bar;$bar--; // this line will be ignored}finally{$bar++;return $bar;}}echo foo(); //2?>code 3<?phpfunction foo(){$bar = 1;try{throw new Exception('I am Wu Xiancheng.');}catch(Exception $e){return $bar;$bar--; // this line will be ignored}finally{return 100;}}echo foo(); //100?>updown1 fjoggen at gmail dot com ¶10 years agoThis code will turn php errors into exceptions:<?phpfunction exceptions_error_handler($severity, $message, $filename, $lineno) {throw new ErrorException($message, 0, $severity, $filename, $lineno);}set_error_handler('exceptions_error_handler');?>However since <?php set_error_handler()?> doesn't work with fatal errors, you will not be able to throw them as Exceptions.updown0 omnibus at omnibus dot edu dot pl ¶8 years agoJust to be more precise in what Frank found:Catch the exceptions always in order from the bottom to the top of the Exception and subclasses class hierarchy. If you have class MyException extending Exception and class My2Exception extending MyException always catch My2Exception before MyException.Hope this helpsupdown0 jon at hackcraft dot net ¶9 years agoFurther to dexen at google dot me dot up with "use destructors to perform a cleanup in case of exception". The fact that PHP5 has destructors, exception handling, and predictable garbage collection (if there's a single reference in scope and the scope is left then the destructor is called immediately) allows for the use of the RAII idiom./wiki/Resource_Acquisition_Is_Initialization and my own /RAII/ describe this.updown-1 Sawsan ¶4 years agothe following is an example of a re-thrown exception and the using of getPrevious function:<?php$name = "Name";//check if the name contains only letters, and does not contain the word nametry{try{if (preg_match('/[^a-z]/i', $name)){throw new Exception("$name contains character other than a-z A-Z");}if(strpos(strtolower($name), 'name') !== FALSE){throw new Exception("$name contains the word name");}echo "The Name is valid";}catch(Exception $e){throw new Exception("insert name again",0,$e);}}catch (Exception $e){if ($e->getPrevious()){echo "The Previous Exception is: ".$e->getPrevious()->getMessage()."<br/>";}echo "The Exception is: ".$e->getMessage()."<br/>";}?>updown-2 Hayley Watson ¶2 years agoRemember that Exceptions are also objects and can be handled as such; they can be constructed in and returned as values from functions, passed as arguments to other functions, and examined before being thrown. You don't have to throw it as soon as you have constructed it (the stack trace will of course reflect the moment the Exception was constructed, not the moment it was thrown).You might, for example, want to collect additional information to include in YourException but you don't want to clutter up the YourException class or the code containing the "throw" statement by collecting the information there. Or you might want to do something (such as logging) with each Exception that is thrown from a certain region (catch it, pass it to the logging function, then rethrow it).updown-2 Tom Polomsk ¶1 year agoContrary to the documentation it is possible in PHP 5.5 and higher use only try-finally blockswithout any catch block.updown-4 alex dowgailenko [at] g mail . com ¶5 years agoIf you use the set_error_handler() to throw exceptions of errors, you may encounter issues with __autoload() functionality saying that your class doesn't exist and that's it.If you do this:<?phpclass MyException extends Exception{}class Tester{public function foobar(){try{$this->helloWorld();} catch (MyException $e) {throw new Exception('Problem in foobar',0,$e);}}protected function helloWorld(){throw new MyException('Problem in helloWorld()');}}$tester = new Tester;try{$tester->foobar();} catch (Exception $e) {echo $e->getTraceAsString();}?>The trace will only show $tester->foobar() and not the call made to $tester->helloWorld().In other words, if you pass a previous exception to a new one, the previous exception's stack trace is taken into account in the new exception.updown-9 hartym dot dont dot like dot spam at gmail dot com ¶8 years ago@serenity: of course you need to throw exception within the try block, catch will not watch fatal errors, nor less important errors but only exceptions that are instanceof the exception type you're giving. Of course by within the try block, i mean within every functions call happening in try block.For example, to nicely handle old mysql errors, you can do something like this:<?phptry{$connection = mysql_connect(...);if ($connection === false){throw new Exception('Cannot connect do mysql');}/* ... do whatever you need with database, that may mail and throw exceptions too ... */mysql_close($connection);}catch (Exception $e){/* ... add logging stuff there if you need ... */echo "This page cannot be displayed";}?>By doing so, you're aiming at the don't repeat yourself (D.R.Y) concept, by managing error handling at only one place for the whole.ajax++mssql实现的ajax无刷新聊天室,支持html web编辑器。

相关文档
最新文档