PHP 5 adds exception handling modules similar to those in other languages. Exceptions generated in PHP code can be thrown by a throw statement and captured by a catch statement . ( Note: Must be thrown first to obtain)
The code that requires exception handling must be placed inside a try code block to catch possible exceptions.
Each try must have at least one catch corresponding to it.
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.
When an exception is thrown, the code behind it (the code block where the exception was thrown) will not continue, and PHP will attempt to find the first catch to match it.
If an exception is not captured and does not use Set_exception_handler () for the appropriate processing, then PHP will produce a serious error and output uncaught exception ... (The exception is not caught) prompt information.
Let's take a look at the basic properties and methods of the PHP built-in exception class. (not including specific implementations)
[PHP]View Plaincopy
- <?php
- /**
- * exception.php
- *
- * PHP5 properties and methods of the built-in exception classes
- * The following code is only for the purpose of explaining the structure of the built-in exception-handling class, which is not a meaningful piece of code available.
- */
- Class exception{
- protected $message = ' Unknown exception '; //exception information
- protected $code = 0; //user Custom exception code
- protected $file; //filename of exception occurred
- protected $line; //code line number where the exception occurred
- function __construct ($message = null, $code = 0);
- Final function getMessage (); //Return exception information
- Final function GetCode (); //Return exception code (codename)
- Final function getFile (); //Returns the file name of the exception that occurred
- Final function getLine (); //Returns the code line number where the exception occurred
- Final function gettrace (); ///BackTrace () array
- Final function gettraceasstring (); //Gettrace () information that has been rasterized into a string
- //methods that can be overloaded
- function __tostring (); //output-able string
- }
- ?>
Examples are as follows:
Include file error throwing exception
<?php
The wrong demo
try {
Require (' test_try_catch.php ');
} catch (Exception $e) {
echo $e->getmessage ();
}
Correct throwing of exceptions
try {
if (file_exists (' test_try_catch.php ')) {
Require (' test_try_catch.php ');
} else {
throw new Exception (' file is not exists ');
}
} catch (Exception $e) {
echo $e->getmessage ();
}
PHP Learning Try Catch