Handling multiple errors
There is no difference between the error identification or objects returned by abnormal processing and our traditional practice - the value of the error logo or object is not checked. Let us handle the CommandManager and check if the Command directory exists in the constructor.
INDEX_PHP5_2.PHP
Here there are two calls that may cause the program (__construct () and getcommandObject ()). Despite this, we don't need to adjust our customer code. You can add a lot of content in the TRY statement and then process it in the Catch. If the constructor of the CommandManager object throws an exception, the execution abort in the try statement, and then the catch statement is called to capture the relevant exception. Similarly, getcommandObject () is also true. In this way, we have two potential to initiate errors, and a unique statement to process all errors. This makes our code look more tidy and meets the requirements of the wrong handling. Compared with the traditional error method of the previously mentioned PHP, it is obviously very advantageous.
Index_php5_2.PHP latter half section
Note: Although there are two possible places that may be wrong than INDEX_PHP5.PHP, this code is exactly the same.
php // php 5 try {$ mgr = new commandmanager (); // potential error $ cmd = mgr-> getcommandObject ('realcommand'); // another potential error $ cmd-> execute ();} catch (Exception $ E) {// Handle Either Error Here Print $ E-> getMessage (); exit ();}?> There is also a place we did not mention. How do we distinguish between different types of errors? For example, we may want to handle errors that cannot be found in a way, and use another way to handle illegal Command classes.
The Exception class can accept an optional integer error identifier, which is a method that distinguishes different errors in the CATCH statement.
INDEX_PHP5_3.PHP
By passing the parameters of cmdman_illegalclass_error and cmdman_general_error, we can make customer code distinguish between different types of errors and define different processing strategies.
Index_php5_3.php php // PHP 5 try {$ mgr = new commandmanager (); $ cmd = $ mgr-> getcommandObject ('realcommand'); $ cmd-> execute ();} catch (Exception $ e) { IF ($ E-> getCode () == comMMANAGER :: cmdman_general_error) {// no way of recovering die ($ e-> getMessage ());} else f ($ e-> getcode () == CommandManager :: CMDMAN_ILLEGALCLASS_ERROR) {Error_Log ($ E-> GetMessage ()); Print "Attempting Recovery / N"; // Perhaps Attempt To Invoke A Default Command?}?>
We can also use another way to achieve this effect - send a subclass representing different types of abnormalities from the most fundamental Exception class, throw and capture.