SoFunction
Updated on 2025-03-06

PHP object-oriented programming (oop) study notes (IV) - Exception handling class Exception

Exception of use

PHP5 adds exception handling modules similar to other languages. Exceptions generated in PHP code can be thrown by throw statements and caught by catch statements. Code that needs 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. Use multiple catches to catch exceptions generated by different classes. When the try code block no longer throws an exception or the catch cannot be found to match the thrown exception, the PHP code will continue to execute after jumping to the last catch. Of course, PHP allows throwing (throw) exceptions again within the catch code block.

Predefined exception Exception

The Exception class is the base class for all exceptions. We can achieve the purpose of customizing exceptions by derive the Exception class. The following list lists the basic information about Exception.

Copy the codeThe code is as follows:

Exception {
/* Attributes */
protected string $message ;        //Exception message content
protected int $code ;                      //Exception code
protected string $file ;         //The file name that throws the exception
protected int $line ;
/* method */
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )    //Exception constructor
final public string getMessage ( void )
final public Exception getPrevious ( void ) //Return the previous exception in the exception chain
final public int getCode ( void ) //Get exception code
final public string getFile ( void ) //Get the name of the program file where the exception occurred
final public int getLine ( void )                                                                                                                         �
final public array getTrace ( void ) //Get exception tracking information
final public string getTraceAsString ( void ) //Get exception tracking information of string type
public string __toString ( void )
final private void __clone ( void )                                                                                                                        �
}

After understanding Exception, let's try to extend the exception class to implement a custom exception.

Copy the codeThe code is as follows:

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, catch this exception in catch, and finally print "can not connect to the database." Maybe you want to display the reason why the database connection fails. The following is to implement our custom information by extending the exception class.

Copy the codeThe code is as follows:

class MyException extends Exception
{
    protected $ErrorInfo;
//The constructor handles some logic and then passes some information to the base class
    public function __construct($message=null,$code=0)
    {
$this->ErrorInfo = 'Error message for custom error class';
        parent::__construct($message,$code);
    }   
//Providing a method to obtain custom class information
    public function GetErrorInfo()
    {
        return $this->ErrorInfo;
    }
    /**
     *
*You can also add exception logs here, just call them in the above constructor
     *
     */
    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 handling function

The function name called when an uncaught exception occurs is used as a parameter to set_exception_handler. The function must be defined before calling set_exception_handler(). This function accepts a parameter which is a thrown exception object. This can be used to improve the exception logging process mentioned above.

Copy the codeThe code is as follows:

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

1.3. PHP allows throwing (throw) exceptions again in the catch code block.

Copy the codeThe code is as follows:

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

Summarize

The function of exceptions is very powerful, but I don’t think we can arbitrarily abuse the exception mechanism in the project, especially the mechanism of using exception logs in large quantities. This time, it greatly increases the system overhead and reduces the performance of the application. Using error codes, we can conveniently manage error information. When an error message is thrown flatly multiple times, using error code is a scientific choice. We can even use error codes to make error messages support multilingual display.