Php5 program exception handling

Source: Internet
Author: User

How exceptions work:
Try
{
Code handler;
If (code processing error) throw new Exception ('Throw an exception'); // use the throw keyword, followed by an object of Exception
// It must be noted that php5 does not automatically throw an exception
// After an exception is thrown, the following processing program will not be executed
Code handler;
}
Catch Exception $ e
{
Exception Handling;
// For example, echo 'exception '. $ e-> getCode (). ':'. $ e-> getMessage (). 'in '. $ e-> getFile (). 'on line '. $ e-> getLine ();
}

Let's see how the thrown exception-type system is defined.
Class Exception
{
Protected $ message = 'unknown exception ';
Protected $ code = 0;
Protected $ file;
Protected $ line;

Function _ construct ($ message = null, $ code = 0 );

Final function getMessage ();
Final function getCode ();
Final function getFile ();
Final function getLine ();
Final function getTrace ();
Final function getTraceAsString (); // same as getTrace (), except that it is formatted as a string

Function _ toString (); // This method is automatically called when the string representation of the object is required, that is, once an Exception instance is directly output by echo or print, it is called.
}

The attribute of Exception cannot be directly accessed in the calling code. Instead, you must use the get method to obtain the attribute value. Only $ message is used. $ code can be set when the user throws an Exception, the constructor of the Exception class is completed. From the Exception class, we can inherit the Exception class to create our own Exception class. When detecting errors, we will not throw the default Exception object of the system, but our custom Exception class object, however, we can only inherit the attributes of constructors, toString () methods, and Exception.

Class myException extends Exception
{
Function _ toString ()
{
Return '<div class = "error"> exception '. $ this-> getCode (). ':'. $ this-> getMessage (). 'in '. $ this-> getFile (). 'on line '. $ this-> getLine (). '</div>'; // rewrite and throw an exception.
}
}

Call our custom exception classes in code
Try
{
Throw new myException ('error', 10); // For simplicity, a custom exception object is thrown directly.
}
Catch (myException $ e)
{
Echo $ e; // because our custom exception has changed the output mode, enter the exception object directly, the reason is that when an Exception instance is output by echo or print, _ toString () is called ()
}

The single room above introduces exceptions. Next we will introduce exceptions to our database processing class to see how to use them.
<? Php
Class myException extends Exception {
Function _ construct ($ message = null, $ code = 0)
{
Parent: :__ construct ($ message, $ code );
}
Function _ toString ()
{
Return '<div class = "error"> exception '. $ this-> getCode (). ':'. $ this-> getMessage (). 'In File :'. $ this-> getFile (). 'On line :'. $ this-> getLine (). '</div>'; // rewrite and throw an exception.
}
}
Class mydb {
Private $ user; // user Name
Private $ pass; // Password
Private $ host; // database IP address or localhost
Private $ db; // Database Name

// Constructor
Public function _ construct (){
$ Num_args = func_num_args ();

If ($ num_args> 0 ){
$ Args = func_get_args ();
$ This-> host = $ args [0];
$ This-> user = $ args [1];
$ This-> pass = $ args [2];
// Automatically call the database connection after passing in Parameters
$ This-> connect ();
}
}

// Database connection
Private function connect (){
// Exception Handling
Try {
If (! $ This-> db = @ mysql_connect ($ this-> host, $ this-> user, $ this-> pass )){
$ Exceptionstring = "Connection Failed: Host, user name, or Password error ";
Throw new myException ($ exceptionstring, 0); // throw a custom exception object with a parameter error.
}
} Catch (myException $ e ){
Echo $ e;
}
}

// Database selection
Public function selectdb ($ thedb ){
Try {
If ([email =! @ Mysql_select_db]! @ Mysql_select_db [/email] ($ thedb, $ this-> db )){
$ Predictionstring = "Database: <font color = red> $ thedb </font> does not exist ";
Throw new myException ($ exceptionstring, 1 );
}
} Catch (myException $ e ){
Echo $ e;
}
}

// Execute an update, delete
Public function execute ($ thequery ){
Try {
If ([email =! @ Mysql_query]! @ Mysql_query [/email] ($ thequery, $ this-> db )){
$ Predictionstring = "Incorrect SQL statement: <font color = red> $ thequery </font> ";
Throw new myException ($ exceptionstring, 2 );
} Else {
Echo "update/delete:". mysql_affected_rows (). "Row <br/> ";
}
} Catch (myException $ e ){
Echo $ e;
}
}

// Return the inserting result
Public function getrows ($ thequery ){
Try {
If (! $ Aquery = @ mysql_query ($ thequery )){
$ Predictionstring = "Incorrect query statement: <font color = red> $ thequery </font> ";
Throw new myException ($ exceptionstring, 3 );
} Else {
While ($ adata = mysql_fetch_array ($ aquery )){
$ Returnarr [] = $ adata;
}
Return $ returnarr;
}
} Catch (myException $ e ){
Echo $ e;
}
}

// The Destructor closes the connection.
Public function _ destruct (){
Try {
If ([email =! @ Mysql_close]! @ Mysql_close [/email] ($ this-> db )){
$ Exceptionstring = "failed to close the connection ";
Throw new myException ($ exceptionstring, 4 );
}
} Catch (myException $ e ){
Echo $ e;
}
}

}
// Instance type
$ Mydb = new mydb ("localhost", "root", "123456 ");
// Select a database
$ Mydb-> selectdb ("tonlong ");
// Perform the update operation
$ Adata = $ mydb-> execute ("update db_news set hits = hits + 1 where id = 3 ");
// Query output
$ Data = $ mydb-> getrows ("select title from db_news ");
For ($ I = 0; $ I <count ($ data); $ I ++ ){
Echo $ data [$ I] [0]. "<br/> ";
}
?>

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.