PHP Exception Handling

Source: Internet
Author: User
Tags php exception handling

1. PhP5 provides the basic exception handling class, which can be directly used.

<? PHP
Class Exception
{
Protected $ Message = 'Unknown exception '; // Exception Information
Protected $ Code = 0; // User-defined exceptionCode
Protected $ File ; // File Name with exception
Protected $ Line ; // Abnormal code line number

Function _ Construct ( $ Message = Null , $ Code = 0 );

Final Function Getmessage (); // Return exception information
Final Function Getcode (); // Return Exception Code
Final Function GetFile (); // Returns the file name with an exception.
Final Function Getline (); // Returns the line number of the Code with an exception.
Final Function Gettrace (); // Backtrace () array
Final Function Gettraceasstring (); // Gettrace () information formatted into strings

/* Reload Method */
Function _ Tostring (); // Output string
}
?>

Simple usage: (throws an error message through an exception)

Try{
$ Error= 'My error! ';
Throw New Exception($ Error)
}Catch(Exception $ E){
Echo $ E-> Getmessage ();
}

2. We can expand this class to facilitate our use.

 Class Myexception Extends   Exception 
{
// Redefines the constructor to change the message to a required attribute.
Public Function _ Construct ( $ Message , $ Code = 0 ){
// Custom Code

// Make sure all variables are correctly assigned values
Parent ::__ construct ( $ Message , $ Code );
}

// Custom string output style
Public Function _ Tostring (){
Return _ Class __ .":[{ $ This -> Code}]: { $ This -> Message} \ n ";
}

Public Function Customfunction (){
Echo "A custom function for this type of exception \ n ";
}
}

It can be expanded as needed!

Related Article

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.