What is an exception?

An exception is a condition in which the program is not running as expected and is different from the normal process.

For example, if you link to the database, and the parameters are written in the condition that the link does not go up, this is not expected

Can be caught by a try-catch

What is a mistake?

It is a PHP program problem, usually caused by illegal syntax, environment problems, compiler checks, and even cannot run. The usual examples of warming and notice are errors, but at different levels.

Such as:

  • The type of the argument I specified for the function is inconsistent with the argument passed in
  • ArithmeticError
  • In the called file, include “demo.php”, or eval(); Parsing failed due to a syntax error
  • AssertionError This error is generated when the assert is in effect
  • DivisionByZeroError (the denominator is zero) An operation such as division in which the denominator is zero

All but these are exceptions

Exception handling

PHP 7.x defines a Throwable interface and makes most errors and exceptions implement it. PHP 7.x defines a Throwable interface and makes most errors and exceptions implement it. We can throw the error in a try-catch

So in the future, if you want to catch an Exception and you don’t know whether it’s an Error or an Exception, you can throw it like this

Try {... } the catch (Throwable $e) {... }Copy the code

Level of error

Parse error >Fatal error > Waning > Notice > Deprecated

Deprecated Lowest level errors (not recommended, not recommended) occur when using expired functions, and will be Deprecated when the program continues to execute Notice when using undefined variables, constants, or array keys without quotation marks. The program continues with the E_NOTICE // runtime notification. Indicates that the script encountered a condition that might appear to be an error. E_USER_NOTICE // Indicates the notification generated by the user. The error program of the Waning warning level has gone wrong and the code needs to be modified! The program continues with E_WARNING // runtime warning (non-fatal error). E_CORE_WARNING // Warning (non-fatal error) that occurred during PHP initialization startup. E_COMPILE_WARNING E_USER_WARNING // Fatal Error Of the user-generated warning level To interrupt program execution, you can use register_shutdown_function() to trigger an E_ERROR function before the program terminates. Pause script execution E_CORE_ERROR // fatal error during PHP startup initialization E_COMPILE_ERROR // Fatal error at compile time, like when Zend script engine generates an E_ERROR E_USER_ERROR // custom error message. The trigger_error function trigger_error (error type set to E_USER_ERROR) is used to Parse Parse errors. Interrupt program execution and do nothing but modify the INI file and write the error message to the log. E_PARSE // Syntax parsing errors at compile timeCopy the code

Custom error handlers

In some cases, PHP’s own error handlers are not sufficient for our needs, and most of the time, we have to override exception handling manually.

PHP provides us with three functions to help us do this

set_error_handler()

  • Function to host error handlers, and you can customize the error handling process.
  • If an error occurs in the code preceding this function, our custom handler is not called because it is not registered
  • Error_reporting () will fail after this function is set
  • The following levels of errors cannot be handled by user-defined functions: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING this function only catches some of our Warning and Note level errors

set_exception_handler()

  • For exception handling that has not been caught

register_shutdown_function()

  • Function: registers a function that will be executed when PHP terminates
  • Fatal Error, Parse Error, etc. This method is the last function called before the end of PHP script execution. For example, script Error, die(), exit, exception, and normal end are called.
  • If used for error handling, need to cooperateerror_get_last()It gets the last error that happened.
// For example: register_shutdown_function('shutdown'); function shutdown() { if ($error = error_get_last()) { var_dump($error); }} $name; No.Copy the code

Parse error: syntax error, unexpected ‘; ‘in/app/swoole/errorDemo. PHP on line 34 Emmmmm this bullshit? Clearly not implemented?

The reason for this is that before the program is executed, we PHP will check the syntax of our program, and if there are no problems, then we can execute our program.

Our above code doesn’t pass our syntax check, so it just reports an error.

So the question is? When we are in the framework, why is it that the framework is always the framework that gives us an error?

Error handling for the framework

Within the framework, its code is loaded via an entry file. When PHP detects syntax errors, it only checks for errors in our index. PHP file. The code in require is not detected. Handling of some error exceptions is typically defined in the index.php file. When our code fails, it’s an error detected in run-time, and our framework can handle it itself based on the error exception we wrote.

Let’s take an example of exception handling in ThinkPHP5

// [application entry file] index.php namespace think; // Load the base file require __DIR__. '/.. /thinkphp/base.php'; Container::get('app')->run()->send();Copy the code

In our entry file, we load base.php where TP defines its own exception handling

/ / load the Loader class require __DIR__. '/ library/think/Loader. PHP; // Register the automatic loading Loader::register(); Error::register(); If (interface_exists('Psr\Log\LoggerInterface')) {//doSomething} // Register class alias Loader::addClassAlias([ //doSomething ]); Void */ public static function register() {error_reporting(E_ALL); set_error_handler([__CLASS__, 'appError']); set_exception_handler([__CLASS__, 'appException']); register_shutdown_function([__CLASS__, 'appShutdown']); }Copy the code

You can see that TP registers the Exception handling mechanism in the entry script, registering Error, Exception and Shutdown handling respectively. All subsequent exceptions are not PHP’s original exception but TP’s custom exception.

The above content hope to help you, more free PHP large factory PDF, PHP advanced architecture video materials, PHP wonderful good article can be wechat search concern: PHP open source community

2021 Gold three silver four big factory interview true question collection, must see!

Four years essence OF PHP technical articles collation collection – PHP framework

A collection of four years of quintessential PHP technology articles – Microservices Architecture

Four years of quintessential PHP technology – distributed architecture

Four years of quintessential PHP technology – high concurrency scenarios

Four years essence OF PHP technical articles collation collection – database