PHP Object Oriented Programming (oop) Learning Notes of Four Exception Handling Class Exception

  • 2021-06-29 10:28:31
  • OfStack

Use exception

PHP5 adds exception handling modules similar to other languages.Exceptions generated in PHP code can be thrown by an throw statement and caught by an catch statement.Code that requires exception handling must be placed in the try code block in order to catch possible exceptions.Each try corresponds to at least one catch block.Using multiple catchs, you can catch exceptions from different classes.When the try code block no longer throws an exception or no catch matches the thrown exception, the PHP code continues execution after jumping to the last catch.Of course, PHP allows an (throw) exception to be thrown again within the catch code block.

Predefined Exception Exception

The Exception class is the base class for all exceptions, and we can customize exceptions by deriving the Exception class.The following list lists the basic information for Exception.


Exception {
    /*  attribute  */
    protected string $message ;        // Exception message content 
    protected int $code ;            // Exception Code 
    protected string $file ;        // File name throwing exception 
    protected int $line ;            // Line number in the file where an exception was thrown 
    /*  Method  */
    public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )    // Exception Constructor 
    final public string getMessage ( void )            // Get exception message content 
    final public Exception getPrevious ( void )        // Return the first in the exception chain 1 Exceptions 
    final public int getCode ( void )                // Get exception code 
    final public string getFile ( void )            // Get the name of the program file in which the exception occurred 
    final public int getLine ( void )                // Gets the line number of the exception code in the file 
    final public array getTrace ( void )            // Get exception tracking information 
    final public string getTraceAsString ( void )    // Get exception tracking information for string type 
    public string __toString ( void )                // Convert Exception Object to String 
    final private void __clone ( void )                // Abnormal Cloning 
}

After learning about Exception, let's try extending the exception class to implement a custom exception.


function connectToDatabase()
{    
    if(!$link = mysql_connect("myhost","myuser","mypassw","mybd"))
    {
        throw new Exception("could not connect to the database.");
    }
}
try
{
    connectToDatabase();
}
catch(Exception $e)
{echo $e->getMessage();
}

Here we throw an exception of type Exception of the class and caught it in catch, which resulted in the printing of "could not connect to the database."You might also want to display information about why the database connection failed.Below and by extending the exception class to achieve our custom information.


class MyException extends Exception
{
    protected $ErrorInfo;
    // Processing in Constructors 1 Some logic, and then 1 Some information is passed to the base class 
    public function __construct($message=null,$code=0)
    {
        $this->ErrorInfo = ' Error information for custom error classes ';
        parent::__construct($message,$code);
    }    
    // Provides a way to get custom class information 
    public function GetErrorInfo()
    {
        return $this->ErrorInfo;
    }
    /**
     *
     * Exception logs can also be added here , Just call it in the constructor above 
     *
     */
    public function log($file)
    {
        file_put_contents($fiel,$this->__toString(),FILE_APPEND);
    }
}
function connectToDatabase()
{    
    throw new MyException("ErrorMessage");
}
try
{    
    connectToDatabase();
}
catch(MyException $e)
{    
    echo $e->getMessage() . "\n";
    echo $e->GetErrorInfo();
}

set_exception_handler sets a user-defined exception handler

The name of the function called when an uncaught exception occurs is set_exception_Parameters for handler.This function must call set_exception_handler() was previously defined.The function accepts a parameter that is an exception thrown.This can be used to improve the exception logging processing mentioned above.


function ExceptionLogger($exception)
{
    $file='ExceptionLog.log';
    file_put_contents($fiel,$exception->__toString(),FILE_APPEND);
}
set_exception_handler(ExceptionLogger);

1.3, PHP allows another (throw) exception to be thrown within the catch code block.


try
{
    #code...
}
catch(Exception $e)
{
    if($e->getCode() == 999)
    {
        # Conduct 1 Some operations 
    }
    else
    {
        throw $e;
    }
}

summary

Exceptions are powerful, but don't think that we can arbitrarily abuse them in our projects, especially those that use exception logs a lot, which can dramatically increase system overhead and degrade application performance.Error codes allow us to easily manage error information. When an error message is thrown flat multiple times, using error codes is a scientific choice.We can even enable error messages to be displayed in multiple languages through error codes.


Related articles: