PHP 7 Error Exception level

Source: Internet
Author: User
Tags zend

This article introduces the content is about PHP7 error anomaly level, has a certain reference value, now share to everyone, the need for friends can refer to

PHP 7 Error Exception level


Explore the exception hierarchy for PHP 7

In the past PHP, it is almost impossible to deal with fatal errors. A fatal error will simply terminate the execution of the script without invoking the Set_error_hander () error handler.

In PHP 7, when a fatal or recoverable error (E_error and e_recoverable_error) occurs, the exception is caught instead of aborting the script. In certain cases, there are still fatal errors, such as low memory, and the script will be aborted as soon as before. An uncaught exception in PHP 7 is still a fatal error. This means that if an uncaught exception is not caught in PHP 5.x, it is still a fatal error in PHP 7.

Note, for example, that warnings or notification errors remain unchanged in PHP 7, and only fatal errors or recoverability errors can throw exceptions.

The throwing of fatal or recoverable errors does not extend from the Exception class. This separation is to prevent the existing PHP 5.x code from receiving the error of the exception call to the terminating program. A fatal or recoverable error throws an exception that instantiates a new Exception class: Error. As with other exception classes, the Error class that is captured will be processed after the last block has been executed.

The exception class level for PHP 7 is different than PHP 7 alpha-2, and the fatal and recoverable errors thrown are instantiated in the Engineexception class, and the Enginexception class does not inherit from Exception. Both Exception and engineexception inherit from Baseexception.

Throwable

In order to federate these two anomalous branches, both Exception and Error implement a new interface, Throwable.

The new exception levels in PHP 7 are as follows:

Throwable//(interface)    |-Exception implements Throwable |    -Error implements Throwable        | | TypeError extends Error         |-ParseError extends error//compile-time Errors        |-Arithmeticerro R extends Error            |-pisionbyzeroerror extends arithmeticerror        |-Assertionerror extends error

If you define the Throwable interface in PHP 7, it should be similar to the following code.

Interface throwable{public    function GetMessage (): string;    Public Function GetCode (): int;    Public Function GetFile (): string;    Public Function GetLine (): int;    Public Function Gettrace (): array;    Public Function Gettraceasstring (): string;    Public Function GetPrevious (): Throwable;    Public Function __tostring (): string;}

This interface should be familiar. Throwable specific methods are the same as Exception. The only difference is that throwable::getprevious () will return Throwable Exception and the constructor of the Error class will receive an instance of Throwable as the previous exception.

Throwable can use an old catch exception or an Error object in a Try/catch block (more exception types may be caught in the future). Remember, it is more recommended to capture more specific exception classes and take appropriate action. However, in some cases, a wide range of catch exceptions (such as log or frame error handling) is required. In PHP 7, these exception-capturing blocks are better suited to use throwable instead of Exception.

try {    //Code that could throw an Exception or Error.} catch (Throwable $t) {    //Handle Exception}

Custom classes cannot implement the Throwable plug-in, which is due to predictability and consistency: only instantiating excetion and the Error class can throw exceptions. In addition, the exception carries information about the object that was created in the stack. Custom classes do not automatically have parameters to hold information.

Throwable can extended to create package-specific interfaces or add additional methods. Only the class that inherits the Exception or the Error can implement the plugin that expands the throwable.

Interface Mypackagethrowable extends Throwable {}class Mypackageexception extends Exception implements mypackagethrowable {}throw new mypackageexception ();

Error

In PHP 5, all errors in the next release are fatal or recoverable fatal errors, and in PHP 7 the instantiation of the error is thrown. Like other exception error objects can be captured through the Try/catch program block.

$var = 1;try {    $var->method ();//Throws An Error object in PHP 7.} catch (Error $e) {    //Handle Error}

In general, the previous fatal error will throw an instantiation of the error base class, but some errors will throw more exact error subclasses: TypeError, ParseError, and Assertionerror.

TypeError (type error)

TypeError instantiation is thrown by arguments and formal parameters when the function is called when the formal parameter and argument type are inconsistent (inconsistent with the parameter types defined in the method) will throw an TypeError instance.

function Add (int $left, int $right) {    return $left + $right;} try {    $value = Add (' Left ', ' right '),} catch (TypeError $e) {    echo $e->getmessage (), "\ n";}

The resulting output:

Argument 1 passed to add () must is of the type Integer, string given

ParseError (parsing error)

The included/required file, or the code in eval () contains a syntax error, ParseError will be thrown.

try {    require ' file-with-parse-error.php ';} catch (ParseError $e) {    echo $e->getmessage (), "\ n";}

Arithmeticerror (arithmetic error)

There are two cases of throwing a arithmeticerror error: a negative displacement, or using php_int_min as a molecule, 1 doing the denominator call INTP () (Php_ini_min/1 return value is floating-point).

try {    $value = 1 <<-1;} catch (Arithmeticerror $e) {    echo $e->getmessage (), "\ n";}

Pisionbyzeroerror (denominator 0)

Using INTP () or remainder (%) will throw a pisionbyzeroerror error when the denominator is zero. Note that except for 0, only one warning is generated and the result is NaN.

try {    $value = 1 0;} catch (Pisionbyzeroerror $e) {    echo $e->getmessage (), "\ n";}

Assertionerror (assertion)

A assertionerror error is thrown when the condition set by the ASSERT () is not met.

Ini_set (' zend.assertions ', 1); Ini_set (' Assert.exception ', 1); $test = 1;assert ($test = = = 0);

Does not satisfy the condition set by the Assert (), throws a assertionerror error, and assert.exception = 1, the exception output is as follows:

Fatal error:uncaught Assertionerror:assert ($test = = = 0)

ASSERT () is only executed and would only throw an assertionerror if assertions be enabled and set to throw exceptions with INI settings zend.assertions = 1 and assert.exception = 1.

Use Error

Users can create their own error classes as an extension of the error base class. This can be an important issue: what scenarios should throw a subclass instance of the Exception class, and in what situations should the subclass instances of the Error class be thrown?

Because the error object should not be processed in the program's run, it should be rare to catch the wrong object. In general, the wrong object should capture and record it, perform the necessary cleanup, and show the user the error message.

Write code that is compatible with PHP 5.x and 7 Exceptions classes

Using the same code to catch exceptions in PHP 5.x and 7, you can use multiple capture blocks of code, first capturing Throwable, and then Exception. Once you do not need to maintain a PHP 5.x system, blocks of code can be immediately cleaned out.

try {    //Code that could throw an Exception or Error.} catch (Throwable $t) {    //Executed only in PHP 7, would not MA tch in PHP 5.x} catch (Exception $e) {    ///Executed only in PHP 5.x, won't is reached in PHP 7}

English Original: trowski.com/2015

Although this article is humble, but also the author Labor, reproduced also please keep this article link: http://cyleft.com/?p=721

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.