Exceptions

Keywords: PHP PDO SQL Database

nested exception

Before we learn about SPL exceptions, let's take a look at nested exceptions. As the name implies, nested exceptions are nested inside the Exception. An Exception is thrown, and an Exception is thrown after the catch arrives. In this case, nested exceptions can be obtained by the getPrevious method of the Exception base class;

<?php

class DBException extends Exception
{

}

class Database
{
    /**
     * @var PDO object setup during construction
     */
    protected $_pdoResource = null;

    public function executeQuery($sql)
    {
        try {
            throw new PDOException('PDO error');
        } catch (PDOException $e) {
            throw new DBException('Query was unexecutable', null, $e);
        }
        return $numRows;
    }
}

try {
    $sql = 'select * from user';
    $db = new Database('PDO', $connectionParams);
    $db->executeQuery($sql);
} catch (DBException $e) {
    echo 'General Error: ' . $e->getMessage() . "\n";
    // Call getPrevious() of caught exception to get nested exception
    $pdoException = $e->getPrevious();
    echo 'PDO Specific error: ' . $pdoException->getMessage() . "\n";
}

SPL anomaly

Briefly describe the advantages of SPL exceptions:

  1. It can provide classification for exception throwing and facilitate subsequent selective catch exceptions;
  2. The semantics of exceptions is more specific. At first glance, BadFunctionCallException can be seen as an error thrown by an undefined method calling an error;

There are a total of 13 new exception types in SPL. Two of these can be considered base classes: logical exception and runtime exception; both inherit php exception classes. The rest of the methods can be logically divided into three groups: dynamic call group, logical group and runtime group.

The dynamic call group contains exceptions BadFunctionCallException and BadMethodCallException, which are subclasses of BadFunctionCallException (subclass of LogicException).

// OO variant 
class Foo 
{ 
    public function __call($method, $args) 
    { 
        switch ($method) { 
            case 'doBar': /* ... */ break; 
            default: 
                throw new BadMethodCallException('Method ' . $method . ' is not callable by this object'); 
        } 
    } 
  
} 
  
// procedural variant 
function foo($bar, $baz) { 
    $func = 'do' . $baz; 
    if (!is_callable($func)) { 
        throw new BadFunctionCallException('Function ' . $func . ' is not callable'); 
    } 
} 

The logic al group contains exceptions: DomainException, InvalidArgumentException, LengthException, OutOfRangeException.

The runtime group contains exceptions:
It consists of OutOfBoundsException, overflow exception, RangeException, UnderflowException, and unexpected valueexception.

class Foo 
{ 
    protected $number = 0; 
    protected $bar = null; 
  
    public function __construct($options) 
    { 
        /** This method throws LogicException exception**/ 
    } 
      
    public function setNumber($number) 
    { 
        /** This method throws LogicException exception**/ 
    } 
      
    public function setBar(Bar $bar) 
    { 
        /** This method throws LogicException exception**/ 
    } 
      
    public function doSomething($differentNumber) 
    { 
        if ($differentNumber != $expectedCondition) { 
            /** Here, a LogicException exception is thrown**/ 
        } 
          
        /** 
         * Here, this method throws a RuntimeException exception 
         */  
    } 
  
} 

Custom other exceptions

class ThrowableError extends \ErrorException
{
    public function __construct(\Throwable $e)
    {
        // The exception classification can be determined by instanceof (make a mapping)
        if ($e instanceof \ParseError) {
            $message  = 'Parse error: ' . $e->getMessage();
            $severity = E_PARSE;
        } elseif ($e instanceof \TypeError) {
            $message  = 'Type error: ' . $e->getMessage();
            $severity = E_RECOVERABLE_ERROR;
        } else {
            $message  = 'Fatal error: ' . $e->getMessage();
            $severity = E_ERROR;
        }
    }
}

Link reference

http://cn.php.net/manual/zh/c...
http://cn.php.net/manual/zh/s...
http://www.oschina.net/transl...

Posted by mdowling on Fri, 08 Nov 2019 10:15:14 -0800