PHP 5 adds an exception handling module similar to other languages. Exceptions in PHP code can be thrown by throw statements and captured by catch statements. All codes that require exception handling must be placed in the try code block to capture Possible exceptions. Each try must have at least one catch corresponding to it. Multiple catch methods can capture exceptions generated by different classes. When the try code block does not throw an exception or the catch Code cannot be found to match the exception thrown, the PHP code will continue to be executed after the jump to the last catch. Of course, PHP allows another throw exception to be thrown in the catch code block.
PHP 5 provides basic exception handling classes that can be used directly.
<? Phpclass Exception {protected $ message = 'unknown exception'; // exception information protected $ code = 0; // User-Defined Exception code protected $ file; // name of the file with an exception protected $ line; // The code line with the exception function _ construct ($ message = null, $ code = 0); final function getMessage (); // return the exception message final function getCode (); // return the Exception Code final function getFile (); // return the file name final function getLine () with an exception (); // return the code line number final function getTrace (); // ba Cktrace () array final function getTraceAsString (); // getTrace () information that has been formatted into a string/* reload Method */function _ toString (); // output string}?>
Throw an error message through an exception:
try { $error = 'my error!'; throw new Exception($error)} catch (Exception $e) { echo $e->getMessage();}
We can expand this class to facilitate our use:
Class MyException extends Exception {// redefine the constructor to change the message to the public function _ construct ($ message, $ code = 0) attribute that must be specified) {// custom code // ensure that all variables are correctly assigned 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 ";}}
This class can be expanded as needed.