In the last article we mentioned that errors occur during compilation and syntax execution. They have nothing to do with logic and should not occur when programmers code code. In other words, these errors should be avoided in the online environment. Catch catch catch catch catch Exceptions are the opposite.

What is an exception?

An exception is a condition that does not meet expectations in the execution of a program. It is usually allowed to occur and handled by the appropriate exception handler. Of course, you can choose to ignore exception handling, but just like a serious error, the code will stop running immediately. Exceptions are errors in business logic, which are basically man-made by us.

Let’s start with a simple code that looks at throwing and catching exceptions:

function test()
{
    throw new Exception('This is test Error... ');
}

try {
    test();
} catch (Exception $e) {
    print_r($e);
}
Copy the code

We throw an exception through a throw, and then wrap the method around a try… Catch block to catch thrown exceptions. That’s the basic structure of the anomaly.

From here, we can see that exceptions are basically thrown manually and handled externally. Inside PHP, most exceptions are thrown in classes, which is the idea of object-oriented error handling. For example, the PDO class:

try {
    // $pdo = new PDO(); // Fatal error: Uncaught ArgumentCountError: PDO::__construct() expects at least 1 parameter, 0 given
    $pdo = new PDO(' ');
} catch (PDOException $e) {
    print_r($e); // invalid data source name
}
Copy the code

Note that the above commented line of code, passing no parameters is an error and cannot be caught. And passed the wrong parameters, is an exception, in the PDO class source found that the parameters are not thrown. It’s up to the higher-level code, us callers, to capture.

Next, let’s look at the use of custom exception classes and finally statement blocks.

Custom Exception classes inherit from the Exception class, which can be considered the base class for all exceptions. Its structure is as follows:

class Exception
{
    protected $message = 'Unknown exception';   // Exception information
    private   $string;                          // __toString cache
    protected $code = 0;                        // User-defined exception code
    protected $file;                            // Name of the exception file
    protected $line;                            // The line of code where the exception occurred
    private   $trace;                           // backtrace
    private   $previous;                        // previous exception if nested exception

    public function __construct($message = null.$code = 0.Exception $previous = null);

    final private function __clone();           // Cannot be copied. If the clone class is abnormal, a fatal error will be generated

    final public  function getMessage();        // Return an exception message
    final public  function getCode();           // Return an exception code
    final public  function getFile();           // Returns the name of the exception
    final public  function getLine();           // Return the line of code where the exception occurred
    final public  function getTrace();          / / backtrace () array
    final public  function getPrevious();       // Previous exception
    final public  function getTraceAsString();  GetTrace () is formatted as a string

    // Overrideable
    public function __toString();               // A printable string
}
Copy the code

From the class definition above, we can see that we can override constructors and __toString() methods, as well as use some protected properties. So let’s define a custom exception class.

class TestException extends Exception
{
    protected $code = 200;

    public function __construct($message = null.$code = 0.Exception $previous = null){
        $this->message = 'TestException:' . $message;
    }

    public function __toString(){
        return 'code: ' . $this->code . '; ' . $this->message; }}function test2()
{
    throw new TestException('This is test2 Error... ');
}

try {
    test2();
} catch (TestException $e) {
    echo $e, PHP_EOL; // code: 200; TestException: This is test2 Error...
}
Copy the code

Most PHP frameworks have a component or ability to customize exceptions. Since modern frameworks are object-oriented, exceptions are defined in more detail. Different components provide different exception classes to encapsulate exceptions.

Next comes the finally keyword. There is nothing more to be said about this. The finally keyword has the characteristic of executing the contents of the code block defined by it, regardless of whether an exception occurs.

try {
    test2();
} catch (TestException $e) {
    echo $e, PHP_EOL; 
} finally {
    echo 'continue this code ... ', PHP_EOL;
}
// code: 200; TestException: This is test2 Error...
// continue this code ...
Copy the code

With that said, let’s finally combine this with the above to handle the division by 0 exception thrown. As stated at the beginning of this article, errors are to be avoided and exceptions are in the logical business. So when we receive an argument that needs to be divided, we can check whether the number is 0. If it is 0, we can throw an exception and let the upper caller handle it. If it is not 0, we can just let it divide normally.

function test3($d)
{
    if ($d= =0) {
        throw new Exception('The divisor cannot be zero.');
    }
    return 1 / $d;
}

try {
    echo test3(2), PHP_EOL;
} catch (Exception $e) {
    echo 'Excepition:' . $e->getMessage(), PHP_EOL;
} finally {
    echo 'finally: Continue execution! ', PHP_EOL;
}

/ / 0.5
// finally: continue execution!

try {
    echo test3(0), PHP_EOL;
} catch (Exception $e) {
    echo 'Excepition:' . $e->getMessage(), PHP_EOL;
} finally {
    echo 'finally: Continue execution! ', PHP_EOL;
}

Excepition: The divisor cannot be 0
// finally: continue execution!
Copy the code

conclusion

So much for the use of exception correlation. From these two articles, I believe you have gained some intuition about errors and exceptions in PHP. In the following articles, we will compare errors and exceptions and explain how PHP7 has improved on errors. Content is still wonderful, worth looking forward to oh!!

Test code: github.com/zhangyue050…

Reference documents: www.cnblogs.com/init-007/p/… www.php.net/manual/zh/l… www.php.net/manual/zh/c… www.php.net/manual/zh/l…