Home >Backend Development >PHP Tutorial >PHP5 exception handling mechanism using the Throw keyword_PHP tutorial
After creating an Exception object, you can return the object, but it should not be used in this way. A better method is to use the throw keyword instead. throw is used to throw exceptions:
throw new Exception("my message", 44 );
Throw aborts the execution of the script and makes the related Exception object available to client code.
The following is the improved getCommandObject() method:
index_php5.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 PHP5's Reflection API to determine whether the given class belongs to the Command type. Executing this script under the wrong path will report an error like this:
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 results in a fatal error. This means that classes that use exceptions have built-in safety mechanisms. And just using an error flag cannot have such functionality. Failure to handle error flags will only cause your script to continue execution with the wrong value.