PHP Object-oriented programming (OOP) learning notes (iv)-Exception handling class exception_php instances

Source: Internet
Author: User
Using exceptions

PHP5 adds an exception handling module similar to other languages. Exceptions generated in PHP code can be thrown by a throw statement and captured by a catch statement. Code that requires exception handling must be placed inside a try code block to catch possible exceptions. Each try corresponds to at least one catch block. You can use multiple catches to catch exceptions that are generated by different classes. When the try code block no longer throws an exception or cannot find a catch that matches the thrown exception, the PHP code resumes execution after jumping to the last catch. Of course, PHP allows you to throw (throw) exceptions again within a catch code block.

Pre-defined exception Exception

The Exception class is the base class for all exceptions, and we can derive the Exception class to achieve the purpose of the custom exception. The following checklist lists the basic information for Exception.

Copy the Code code as follows:
Exception {
/* Properties */
protected string $message; Exception message Content
protected int $code; Exception code
protected string $file; The file name that throws the exception
protected int $line; Throws the line number of the exception in the file
/* Method */
Public __construct ([string $message = "" [, int $code = 0 [, Exception $previous = NULL]])//Exception constructor
Final public string getMessage (void)//Get Exception message contents
Final public Exception getprevious (void)//Returns the previous exception in the chain of exceptions
Final public int getcode (void)//Get Exception code
Final public string getFile (void)//Gets the program file name of the exception that occurred
Final public int getLine (void)//Gets 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 for string types
public string __tostring (void)//Convert exception object to string
Final private void __clone (void)//Exception clone
}

Once you know Exception, let's try extending the Exception class to implement a custom exception.

Copy the Code code 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 the class Exception type, and catch the exception in the catch, and finally print out "could not connect to the database." Maybe you want to. Displays information about the reason for the database connection failure. Below and by extending the exception class to implement our custom information.

Copy the Code code 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);
}
Provides methods for getting custom class information
Public Function GetErrorInfo ()
{
return $this->errorinfo;
}
/**
*
* The Exception Log 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 setting a user-defined exception handling function

When an uncaught exception occurs, the function name that is called as the Set_exception_handler parameter. The function must be defined before calling Set_exception_handler (). The function takes a parameter, which is an exception object that is thrown. This can be used to improve the Exception log processing mentioned above.

Copy the Code code as follows:
function Exceptionlogger ($exception)
{
$file = ' ExceptionLog.log ';
File_put_contents ($fiel, $exception->__tostring (), file_append);
}
Set_exception_handler (Exceptionlogger);

1.3. PHP allows you to throw (throw) exceptions again within a catch code block.

Copy the Code code as follows:
Try
{
#code ...
}
catch (Exception $e)
{
if ($e->getcode () = = 999)
{
#进行一些操作
}
Else
{
Throw $e;
}
}

Summarize

The functionality of the exception is very powerful, but not for the misuse of the exception mechanism that we can arbitrarily abuse in the project, especially the large number of mechanisms that use the Exception log, which greatly increases system overhead to reduce the performance of the application. With error codes we can easily manage error messages, and when an error message is thrown multiple times, using the error code is a scientific choice. We can even use the error code to let the error message also support multi-language display.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.