Use the throw keyword
After an exception object is created, you can return the object, but you should not use it like this. A better way is to use the throw keyword instead. Throw is used to throw an exception:
throw new Exception( "my message", 44 );
Throw suspends the execution of the script and makes the exception object available to the client code.
The following are the improvementsgetCommandObject()
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 reflection API of PhP5 to determine whether the given class belongsCommand
Type. If you execute this script in the wrong path, the following error will be reported:
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, a fatal error occurs when an exception is thrown. This means that a security mechanism is built in the abnormal class. Using only one error mark does not support this function. If the error mark fails to be processed, your script will use the error value to continue execution.