PHP Try-catch Statement
To further handle the exception, we need to use the Try-catch statement----include a try statement and at least one catch statement. Any code that invokes a method that might throw an exception should use a try statement. Catch statements are used to handle exceptions that may be thrown. Here's how we handle the exception thrown by Getcommandobject ():
<?php
try {
$mgr = new Commandmanager ();
$cmd = $mgr->getcommandobject ("Realcommand");
$cmd->execute ();
} catch (Exception $e) {
print $e->getmessage ();
Exit ();
>
As you can see, by using the Throw keyword and the try-catch statement together, we can avoid the error marking the value returned by the pollution class method. Because "exception" itself is a type of PHP that is different from any other object, it does not create confusion.
If an exception is thrown, the script in the Try statement stops executing, and then immediately moves to the script in the catch statement.
If the exception is thrown and is not captured, a fatal error is generated.