What is the difference between Error and Exception in PHP
Most of the information on the difference between error and exception on the Internet is explained by Java. It seems that the exception handling process of PHP is similar to that of Java. Let's follow the editor to learn the difference and capture of error and exception in PHP. Friends who need it can refer to it. refer to.
Write a piece of JSON parsing code. Since the data source cannot guarantee that it is JSON, the parsing may fail. However, PHP's json_decode will not report an error when it encounters a string that cannot be parsed, and will directly return nothing. And even if it can be parsed, I can't believe that the fields inside are always consistent. Therefore, it is not only necessary to determine whether it can be parsed into JSON, but also whether fields are missing. Out of laziness, I would like to just catch the exception, for example, to catch
Trying to get property of non-object
However, the following try catch I couldn't catch the exception
try { // Code that may throw an Exception or Error. } catch (\Exception $t) { // Handle exception }
After searching Google, I found out that in addition to Exception, there is also the concept of Error in PHP, and Trying to get property of non-object unfortunately falls into the category of Error.
The difference between error and exception in PHP
I have read several introductory articles about the difference between PHP error and exception, but I feel that they have not touched the point. I suddenly thought, why do I need to know the difference between them, because I think there is something wrong with this design. For example, in the PHP5 era, try catch can only catch Exception, but not Error. I really can't understand what is the meaning of this design of PHP 5? The way PHP7 handles it shows that my point of view is correct. Therefore, I have no interest in delving into its original design ideas.
New features of PHP 7
From now on, most of the errors are reported through the exception class Error.
That is, PHP 7 starts , Error and Exception both inherit from Throwable.
From the inheritance relationship of Throwable, we can see that Error and Exception are in a flat relationship.
interface Throwable |- Error implements Throwable |- ArithmeticError extends Error |- DivisionByZeroError extends ArithmeticError |- AssertionError extends Error |- ParseError extends Error |- TypeError extends Error |- ArgumentCountError extends TypeError |- Exception implements Throwable |- ClosedGeneratorException extends Exception |- DOMException extends Exception |- ErrorException extends Exception |- IntlException extends Exception |- LogicException extends Exception |- BadFunctionCallException extends LogicException |- BadMethodCallException extends BadFunctionCallException |- DomainException extends LogicException |- InvalidArgumentException extends LogicException |- LengthException extends LogicException |- OutOfRangeException extends LogicException |- PharException extends Exception |- ReflectionException extends Exception |- RuntimeException extends Exception |- OutOfBoundsException extends RuntimeException |- OverflowException extends RuntimeException |- PDOException extends RuntimeException |- RangeException extends RuntimeException |- UnderflowException extends RuntimeException |- UnexpectedValueException extends RuntimeException
Capture the method of Trying to get property of non-object
try { // Code that may throw an Exception or Error. } catch (\Throwable $t) { // Handle exception }
Compatible with both PHP 5 and PHP 7 writing methods
try { // Code that may throw an Exception or Error. } catch (\Throwable $t) { // Executed only in PHP 7, will not match in PHP 5.x } catch (\Exception $e) { // Executed only in PHP 5.x, will not be reached in PHP 7 }
Some built-in methods
interface Throwable
{ public function getMessage(): string; // Error reason public function getCode(): int; // Error code public function getFile(): string; // Error begin file public function getLine(): int; // Error begin line public function getTrace(): array; // Return stack trace as array like debug_backtrace() public function getTraceAsString(): string; // Return stack trace as string public function getPrevious(): Throwable; // Return previous `Trowable` public function __toString(): string; // Convert into string }
Record the specific information of the exception
For example
Error code file, line number specific error message error type
Use More precise capture, or broader capture
Or scoring situation
For example, MySQL's unique index exception, I am used to precise capture. Because it requires special handling.
In most other cases, I think just capture Throwable broadly. The reason is that try catch is usually used to ignore exceptions, such as some low-probability exceptions that do not affect logic. There is no need to handle it, so the specific exception is not too important, as long as the log is recorded.
Recommended learning: php video tutorial
The above is the detailed content of What is the difference between Error and Exception in PHP. For more information, please follow other related articles on the PHP Chinese website!

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



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

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

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
