Exception Handling for PHP

Source: Internet
Author: User

Exception Handling for PHP

1. What is an exception?

An exception is an accident or an event that occurs during a program's operation, interrupts the execution of a normal instruction, and jumps to another module to continue execution.

PHP 5 provides a new approach to object-oriented error handling.
Exception handling is used to change the normal process of a script when a specified error (exception) condition occurs. This condition is called an exception.

When an exception is triggered, it usually occurs:
Current code state is saved
Code execution is switched to the pre-defined exception handler function
Depending on the situation, the processor might start executing code from the saved code State,
Terminates script execution, or resumes execution of script from another location in the code
We will show you different error handling methods:
Basic use of exceptions
Creating a custom exception handler
Multiple exceptions
To re-throw an exception
Setting the top-level exception handler

2. Exception Handling Class
PHP has many exception handling classes, where exception is the base class for all exception handling.
Exception::__clone-exception Clone {}
Final private void Exception::__clone (void) attempts to clone the exception, which results in a fatal error.


Exception has several basic properties and methods, including the following:

Message content for exception messages

Code exception Codes
File name that throws an exception
Line throws an exception in the number of lines of the file
Among the methods commonly used are:
Gettrace getting exception tracking information
Gettraceasstring string that gets the exception trace information
GetMessage getting error messages


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.

For example:

extended (Extend) PHP built-in exception handling class
<?php/** * Customizing an exception handling class */class MyException extends exception{//redefine the constructor to make the message a property that must be specified public function __cons Truct ($message, $code = 0, Exception $previous = null) {//Custom code//Make sure all variables are correctly assigned Parent::__construc    T ($message, $code, $previous); }//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 ';    }}/** * Create a class to test the exception handling mechanism */class testexception{public $var;    Const Throw_none = 0;    Const THROW_CUSTOM = 1;    Const THROW_DEFAULT = 2;                function __construct ($avalue = self::throw_none) {switch ($avalue) {case Self::throw_custom:                Throws a custom exception throw new MyException (' 1 is an invalid parameter ', 5);            Break Case Self::throw_default://throws the default exception throw new Exception (' 2 is nOT allowed as a parameter ', 6);            Break                Default://Without exception, create an object $this->var = $avalue;        Break  }}}//Example 1try {$o = new testexception (testexception::throw_custom);} catch (MyException $e) {//catch exception Echo    "Caught my exception\n", $e; $e->customfunction ();} catch (Exception $e) {//ignored echo "Caught Default exception\n", $e;} Continue Executionvar_dump ($o);   Nullecho "\ n";//Example 2try {$o = new testexception (testexception::throw_default);} catch (MyException $e) {//    Cannot match the kind of exception, is ignored echo "caught my exception\n", $e; $e->customfunction ();} catch (Exception $e) {//catch exception echo "Caught Default exception\n", $e;} Execute subsequent code var_dump ($o); Nullecho "\ n";//Example 3try {$o = new testexception (testexception::throw_custom);} catch (Exception $e) {// Catch exception echo "Default Exception caught\n", $e;} Execute subsequent code var_dump ($o); Nullecho "\ n";//Example 4TRy {$o = new testexception (),} catch (Exception $e) {//no exception, ignored echo "Default Exception caught\n", $e;} Execute subsequent code var_dump ($o); Testexceptionecho "\ n";?  >

  



Exception Handling for PHP

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.