After you create a exception object, you can return the object, but this should not be used, and the better way is to use the Throw keyword instead. Throw to throw an exception:
throw new Exception( "my message", 44 );
Throw abort the execution of the script and make the associated exception object available to the client code.
The following is an improved Getcommandobject () method:
index_php5.php
<?php
// PHP 5
require_once('cmd_php5/Command.php');
class CommandManager {
private $cmdDir = "cmd_php5";
function getCommandObject($cmd) {
$path = "{$this->cmdDir}/{$cmd}.php";
if (!file_exists($path)) {
throw new Exception("Cannot find $path");
}
require_once $path;
if (!class_exists($cmd)) {
throw new Exception("class $cmd does not exist");
}
$class = new ReflectionClass($cmd);
if (!$class->isSubclassOf(new ReflectionClass('Command'))) {
throw new Exception("$cmd is not a Command");
}
return new $cmd();
}
}
?>
In the code we use the PHP5 reflection (Reflection) API to determine whether the given class belongs to the command type. Executing this script under the wrong path will report this error:
Fatal error: Uncaught exception 'Exception' with message 'Cannot find command/xrealcommand.php' in /home/xyz/BasicException.php:10
Stack trace:
#0 /home/xyz/BasicException.php(26):
CommandManager->getCommandObject('xrealcommand')
#1 {main}
thrown in /home/xyz/BasicException.php on line 10
By default, throwing an exception causes a fatal error. This means that a security mechanism is built into the class that uses the exception. Instead of using just one error tag, you can't have such a feature. Failure to handle the error tag will only make your script use the wrong value to continue execution.