大家对PHP的异常是什么态度
如题,大家是否会使用PHP的异常,如何使用
网上一些文章,都是介绍语法,没有分享如何真正用好PHP的异常的.
感觉PHP的异常机制不如C++/Java等的好用.
回复内容:
如题,大家是否会使用PHP的异常,如何使用
网上一些文章,都是介绍语法,没有分享如何真正用好PHP的异常的.
感觉PHP的异常机制不如C++/Java等的好用.
由于历史原因PHP很多内置函数都是没有异常,而是通过返回false/-1之类的来表达异常,导致开发者也习惯于采用返回值而非异常来区分(而且php函数的返回值和数组都是那么灵活)
说完不采用异常的理由(虽然没有说全),再来说说为什么异常还是值得使用的。首先需要说明的是,仅考虑语法方面,最新版本的PHP的异常,已经和JAVA等没有区别了。
1. 更丰富的错误信息。使用false/-1之类的返回值,只能让我们知道发生了异常,但不能知道发生了什么异常。即使通过给不同的异常返回不同的状态码,依然不如异常类直观。我们可以通过异常本身的类名来判断是什么异常,通过异常类的message来保存更详细的解释说明,最重要的是,我们可以通过异常的错误栈来判断是哪个文件第几行什么函数发生了问题,谁去调用的它。
2. 保证调用者处理异常。如果你的函数返回的是普通的值,可能出于疏忽,也有可能出于版本兼容问题(调用者根据你的老版本的函数进行开发,而你在新版本的函数里有了新的错误状态码)等情况,调用者忽略了你所返回的错误,那可能造成整个程序存在一些难以发现源头的问题。而异常则保证了调用者必须去处理。
3. 使你的代码逻辑更清晰。设想如果没有finally,针对每次返回都检测异常,并且在每个异常后写一遍释放资源是多么蛋疼的事情。
我自己写的框架是通过捕捉异常来显示错误页面的,其他地方我倒是基本不用异常。
try { require_once($some_file_path); } catch(exception $e) { $smarty->assign("error", $e->getMessage()); $smarty->display("error.tpl"); }

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

In this chapter, we are going to learn the following topics related to routing ?

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Validator can be created by adding the following two lines in the controller.
