PHP 基础
PHP 简介
PHP 入门
PHP 语法
PHP 变量
PHP 常量
PHP 输出和打印
PHP 数据类型
PHP 字符串
PHP 运算符
PHP If…Else
PHP Switch…Case
PHP 数组
PHP 数组排序
PHP 循环
PHP 函数
PHP 数学运算
PHP GET 和 POST
PHP 高级
PHP 日期和时间
PHP 包含文件
PHP 文件系统
PHP 解析目录
PHP 文件上传
PHP 文件下载
PHP Cookies
PHP Sessions
PHP 发送邮件
PHP 表单处理
PHP 表单验证
PHP 过滤器
PHP 错误处理
PHP 类和对象
PHP 魔术常量
PHP JSON 解析
PHP 正则表达式
PHP 异常处理
PHP 和 MySQL 数据库
PHP MySQL 简介
PHP MySQL 连接
PHP MySQL Create Database
PHP MySQL Create Table
PHP MySQL Insert
PHP MySQL Prepared
PHP MySQL Last Inserted ID
PHP MySQL Select
PHP MySQL Where
PHP MySQL Limit
PHP MySQL Order By
PHP MySQL Update
PHP MySQL Delete
PHP MySQL CRUD 应用
PHP MySQL Ajax 搜索
PHP MySQL 登录系统
PHP参考
PHP String Functions
PHP Array Functions
PHP File System Functions
PHP Date/Time Functions
PHP Calendar Functions
PHP MySQLi Functions
PHP Filters
PHP Error Levels
PHP常见问题解答
如何在 PHP 中编写注释
如何在 PHP 中删除字符串中的空格
如何在 PHP 中查找字符串中的字符数
如何在 PHP 中查找字符串中的单词数
如何在 PHP 中删除字符串中的特殊字符
如何在 PHP 中替换字符串中的一个单词
如何在 PHP 中对字符串前面追加
如何在 PHP 中对字符串后面追加
如何在 PHP 中从字符串中提取子串
如何在 PHP 中比较两个字符串
如何在 PHP 中获取当前页面的 URL
如何在 PHP 中通过连接数组值创建字符串
如何在 PHP 中将字符串拆分为数组
如何在 PHP 中合并两个字符串
如何在 PHP 中把字符串转换成小写字母
如何在 PHP 中把字符串转换成大写字母
如何在 PHP 中把字符串的第一个字母转换成大写字母
如何在 PHP 中把特殊的 HTML 实体转换回字符
如何在 PHP 中删除字符串开头的空格
如何在 PHP 中删除字符串结尾的空格
如何在 PHP 中新建一行
如何在 PHP 中查找字符串长度
如何在 PHP 中检查变量是否已设置
如何在 PHP 中检查变量是否为空
如何在 PHP 中检查变量是否为NULL
如何在 PHP 中反转字符串
如何在 PHP 中用另一个字符串替换字符串的一部分
如何在 PHP 中计算子串在字符串中出现的次数
如何在 PHP 中计算数组中的所有元素
如何在 PHP 中打印或回显数组的所有值
如何在 PHP 中显示数组的结构和值
如何在 PHP 中颠倒数组的顺序
如何在 PHP 中检查数组中是否存在值
如何在 PHP 中检查数组中是否存在键
如何在 PHP 中删除数组中的最后一个元素
如何从 PHP 数组中删除第一个元素
如何在 PHP 中为数组的开头添加元素
如何在 PHP 中为数组的末尾添加元素
如何在 PHP 中把两个或多个数组合并成一个数组
如何在 PHP 中按字母顺序对数组值排序
如何在 PHP 中删除数组中的重复值
如何在 PHP 中随机调整数组的顺序
如何在 PHP 中比较两个数组的值
如何在 PHP 中计算数组中数值的总和
如何在 PHP 中删除数组中的空值
如何在 PHP 中用数组值填充下拉列表
如何在 PHP 中获取关联数组的所有键值
如何在 PHP 中获取关联数组的所有值
如何在 PHP 中按键对关联数组排序
如何在 PHP 中按值对关联数组排序
如何在 PHP 中从数组中获取单个值
如何在 PHP 中循环浏览多维数组
如何在 PHP 中从数组中删除元素
如何在 PHP 中检查字符串是否包含特定单词
如何在 PHP 中获取当前日期和时间
如何在 PHP 中进行重定向
如何在 PHP 中删除字符串中的所有空格
如何用 PHP 获取当前年份
如何在 PHP 中将日期从 yyyy-mm-dd 转换为 dd-mm-yyyy 格式
如何在 PHP 中将字符串转换为数字
如何在 PHP 中获取数组的第一个元素
如何在 PHP 中将日期转换为时间戳
如何在 PHP 中为空数组添加元素
如何在 PHP 中把整数转换成字符串
如何用值而不是键删除 PHP 数组元素
如何在 PHP 中将键和值同时推入数组
如何使用 PHP 定期刷新页面
如何从 PHP 字符串中删除最后一个字符
如何从 PHP 脚本返回 JSON
如何让 PHP 显示错误
PHP 异常处理 - php7基础教程 - 笔下光年
网站首页
PHP 异常处理
In this tutorial you will learn how to throw and catch exceptions in PHP. ## What is an Exception An exception is a signal that indicates some sort of exceptional event or error has occurred. Exceptions can be caused due to various reasons, for example, database connection or query fails, file that you're trying to access doesn't exist, and so on. PHP provides a powerful exception handling mechanism that allows you to handle exceptions in a graceful way. As opposed to PHP's traditional [error-handling](http://www.bixiaguangnian.com/manual/php7/3993.html "error-handling") system, exception handling is the [object-oriented](http://www.bixiaguangnian.com/manual/php7/3994.html "object-oriented") method for handling errors, which provides more controlled and flexible form of error reporting. Exception model was first introduced in PHP 5. ## Using Throw and Try...Catch Statements In exception-based approach, program code is written in a `try` block, an exception can be thrown using the `throw` statement when an exceptional event occurs during the execution of code in a `try` block. It is then caught and resolved by one or more `catch` blocks. The following example demonstrates how exception handling works: ```php <?php function division($dividend, $divisor){ // Throw exception if divisor is zero if($divisor == 0){ throw new Exception('Division by zero.'); } else{ $quotient = $dividend / $divisor; echo "<p>$dividend / $divisor = $quotient</p>"; } } try{ division(10, 2); division(30, -4); division(15, 0); // If exception is thrown following line won't execute echo '<p>All divisions performed successfully.</p>'; } catch(Exception $e){ // Handle the exception echo "<p>Caught exception: " . $e->getMessage() . "</p>"; } // Continue execution echo "<p>Hello World!</p>"; ?> ``` You might be wondering what this code was all about. Well, let's go through each part of this code one by one for a better understanding. ## Explanation of Code The PHP's exception handling system has basically four parts: `try`, `throw`, `catch`, and the Exception class. The following list describes how each part exactly works. - The `division()` function in the example above checks if a divisor is equal to zero. If it is, an exception is thrown via PHP's `throw` statement. Otherwise this function perform the division using given numbers and display the result. - Later, the `division()` function is called within a `try` block with different arguments. If an exception is generated while executing the code within the `try` block, PHP stops execution at that point and attempt to find the corresponding `catch` block. If it is found, the code within that `catch` block is executed, if not, a fatal error is generated. - The `catch` block typically catch the exception thrown within the `try` block and creates an object (`$e`) containing the exception information. The error message from this object can be retrieved using the Exception's `getMessage()` method. The PHP's Exception class also provides `getCode()`, `getFile()`, `getLine()` and `getTraceAsString()` methods that can be used to generate detailed debugging information. ```php <?php // Turn off default error reporting error_reporting(0); try{ $file = "somefile.txt"; // Attempt to open the file $handle = fopen($file, "r"); if(!$handle){ throw new Exception("Cannot open the file!", 5); } // Attempt to read the file contents $content = fread($handle, filesize($file)); if(!$content){ throw new Exception("Could not read file!", 10); } // Closing the file handle fclose($handle); // Display file contents echo $content; } catch(Exception $e){ echo "<h3>Caught Exception!</h3>"; echo "<p>Error message: " . $e->getMessage() . "</p>"; echo "<p>File: " . $e->getFile() . "</p>"; echo "<p>Line: " . $e->getLine() . "</p>"; echo "<p>Error code: " . $e->getCode() . "</p>"; echo "<p>Trace: " . $e->getTraceAsString() . "</p>"; } ?> ``` The Exception's constructor optionally takes an exception message and an exception code. While the exception message is typically used to display generic information on what went wrong, the exception code can be used to categorize the errors. The exception code provided can be retrieved later via Exception's `getCode()` method. <div class="callout callout-success mb-3">Tip: Exception should only be used to denote exceptional conditions; they should not be used to control normal application flow e.g., jump to another place in the script at a particular point. Doing that would adversely affect your application's performance.</div> ## Defining Custom Exceptions You can even define your own custom exception handlers to treat different types of exceptions in a different way. It allows you to use a separate `catch` block for each exception type. You can define a custom exception by extending the Exception class, because Exception is the base class for all exceptions. The custom exception class inherits all the properties and methods from PHP's Exception class. You can also add your custom methods to the custom exception class. Let's check out the following example: ```php <?php // Extending the Exception class class EmptyEmailException extends Exception {} class InvalidEmailException extends Exception {} $email = "someuser@example..com"; try{ // Throw exception if email is empty if($email == ""){ throw new EmptyEmailException("<p>Please enter your E-mail address!</p>"); } // Throw exception if email is not valid if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { throw new InvalidEmailException("<p><b>$email</b> is not a valid E-mail address!</p>"); } // Display success message if email is valid echo "<p>SUCCESS: Email validation successful.</p>"; } catch(EmptyEmailException $e){ echo $e->getMessage(); } catch(InvalidEmailException $e){ echo $e->getMessage(); } ?> ``` In the above example we've derived two new exception classes: **EmptyEmailException**, and **InvalidEmailException** from the Exception base class. Multiple `catch` blocks are used to display different error messages, depending on the type of exception generated. Since these custom exception classes inherits the properties and methods from the Exception class, so we can use the Exception's class methods like `getMessage()`, `getLine()`, `getFile()`, etc. to retrieve error information from the exception object. ## Setting a Global Exception Handler As we've discussed earlier in this chapter if an exception is not caught, PHP generates a Fatal Error with an "Uncaught Exception ..." message. This error message may contain sensitive information like file name and line number where the problem occurs. If you don't want to expose such information to the user, you can create a custom function and register it with the `set_exception_handler()` function to handle all uncaught exceptions. ```php <?php function handleUncaughtException($e){ // Display generic error message to the user echo "Opps! Something went wrong. Please try again, or contact us if the problem persists."; // Construct the error string $error = "Uncaught Exception: " . $message = date("Y-m-d H:i:s - "); $error .= $e->getMessage() . " in file " . $e->getFile() . " on line " . $e->getLine() . "\n"; // Log details of error in a file error_log($error, 3, "var/log/exceptionLog.log"); } // Register custom exception handler set_exception_handler("handleUncaughtException"); // Throw an exception throw new Exception("Testing Exception!"); ?> ``` <div class="callout callout-info mb-3">Note: An uncaught exception will always result in script termination. So if you want the script to continue executing beyond the point where the exception occurred, you must have have at least one corresponding catch block for each try block.</div>
上一篇:
PHP 正则表达式
下一篇:
PHP 和 MySQL 数据库