Home > Backend Development > PHP Tutorial > PHP object-oriented programming (oop) study notes (4) - Exception handling class Exception_PHP tutorial

PHP object-oriented programming (oop) study notes (4) - Exception handling class Exception_PHP tutorial

WBOY
Release: 2016-07-13 10:28:23
Original
980 people have browsed it

Usage exception

PHP5 adds exception handling modules similar to other languages. Exceptions generated in PHP code can be thrown by the throw statement and caught by the catch statement. Code that requires exception handling must be placed in a try code block 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 block no longer throws an exception or no catch is found that matches the thrown exception, the PHP code continues execution after jumping to the last catch. Of course, PHP allows exceptions to be thrown again within catch blocks.

Predefined exception Exception

The Exception class is the base class for all exceptions. We can derive custom exceptions by deriving the Exception class. The following list lists basic information about Exception.

Copy code The code is as follows:

Exception {
/* Attributes*/
protected string $message; //Exception message content
protected int $code; //Exception code
protected string $file; //Exception file name
protected int $line; //Exception thrown in the file Line number
/* Method*/
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] ) //Exception constructor
final public string getMessage (void) //Get the exception message content
final public Exception getPrevious (void) //Return the previous exception in the exception chain
final public int getCode (void) //Get the exception code
final public string getFile ( void ) // Get the name of the program file where the exception occurred
final public int getLine ( void ) // Get the line number of the code in the file where the exception occurred
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) //Convert the exception object to a string
final private void __clone (void) //Exceptional clone
}

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

Copy code The 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 type exception, catch this exception in catch, and finally print out "could not connect to the database.". Maybe you want to also display information about why the database connection failed. Next, we implement our custom information by extending the exception class.

Copy code The code is as follows:

class MyException extends Exception
{
protected $ErrorInfo;
//Process some logic in the constructor, and then pass some information to the base class
public function __construct($message =null,$code=0)
{
$this->ErrorInfo = 'Error message of custom error class';
parent::__construct($message,$code);
}                                                                */
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 name of the function called when an uncaught exception occurs as a parameter to set_exception_handler. This function must be defined before calling set_exception_handler(). This function accepts one parameter, which is a thrown exception object. This can be used to improve the exception logging handling mentioned above.




Copy code
The code is as follows:

function ExceptionLogger($exception)

{

$file='ExceptionLog .log';

file_put_contents($fiel,$exception->__toString(),FILE_APPEND);}set_exception_handler(ExceptionLogger);
1.3. PHP allows exceptions to be thrown again within the catch code block.




Copy code

The code is as follows:

try

{

#code...

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



Summary

The exception function is very powerful, but it does not mean that we can abuse the exception mechanism wantonly in the project, especially the mechanism of extensive use of exception logs, which will greatly increase the system overhead and reduce the performance of the application. We can use error codes to easily manage error messages. When an error message is thrown multiple times, using error codes is a scientific choice. We can even use error codes to display error messages in multiple languages.




http://www.bkjia.com/PHPjc/788632.html
www.bkjia.com

true

http: //www.bkjia.com/PHPjc/788632.html

TechArticle

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template