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!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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

Dreamweaver Mac version
Visual web development tools