铁血霸主 2007-8-1 22:20
PHP5的异常处理机制之使用throw关键字
<p><font color="#000000">建立一个Exception对象后你可以将<a href="http://www.phpchina.com/javascript:;" onClick="javascript:tagshow(event, '%B6%D4%CF%F3');" target="_self"><u><strong>对象</strong></u></a>返回,但不应该这样使用,更好的<a href="http://www.phpchina.com/javascript:;" onClick="javascript:tagshow(event, '%B7%BD%B7%A8');" target="_self"><u><strong>方法</strong></u></a>是用throw关键字来代替。throw用来抛出异常: <br><br></font><table align="center" bgcolor="#e3e3e3" border="1" bordercolor="#cccccc" width="90%"><tbody><tr><td><font color="#000000">throw new Exception( "my message", 44 ); </font></td></tr></tbody></table><br><font color="#000000"> throw 将脚本的执行中止,并使相关的Exception对象对客户<a href="http://www.phpchina.com/javascript:;" onClick="javascript:tagshow(event, '%B4%FA%C2%EB');" target="_self"><u><strong>代码</strong></u></a>可用。<br><br> 以下是改进过的getCommandObject() 方法:<br><br> index_php5.php<br><br></font><table align="center" bgcolor="#e3e3e3" border="1" bordercolor="#cccccc" width="90%"><tbody><tr><td><font color="#000000"><?php <br> // <a href="http://www.phpchina.com/javascript:;" onClick="javascript:tagshow(event, 'PHP');" target="_self"><u><strong>PHP</strong></u></a> 5 <br> require_once('cmd_php5/Command.php'); <br> class CommandManager { <br> private $cmdDir = "cmd_php5"; <br><br> function getCommandObject($cmd) { <br> $path = "{$this->cmdDir}/{$cmd}.php"; <br> if (!file_exists($path)) { <br> throw new Exception("Cannot find $path"); <br> } <br> require_once $path; <br> if (!class_exists($cmd)) { <br> throw new Exception("class $cmd does not exist"); <br> } <br><br> $class = new ReflectionClass($cmd); <br> if (!$class->isSubclassOf(new ReflectionClass('Command'))) { <br> throw new Exception("$cmd is not a Command"); <br> } <br> return new $cmd(); <br> } <br> } <br>?></font></td></tr></tbody></table><br><font color="#000000"> 代码中我们使用了PHP5的反射(Reflection)API来判断所给的类是否是属于Command 类型。在错误的路径下执行本脚本将会报出这样的错误:<br><br></font><table align="center" bgcolor="#e3e3e3" border="1" bordercolor="#cccccc" width="90%"><tbody><tr><td><font color="#000000">Fatal error: Uncaught exception 'Exception'with message 'Cannot find command/xrealcommand.php' in/home/xyz/BasicException.php:10 <br>Stack trace: <br>#0 /home/xyz/BasicException.php(26): <br>CommandManager->getCommandObject('xrealcommand') <br>#1 {main} <br>thrown in /home/xyz/BasicException.php on line 10 </font></td></tr></tbody></table><br><font color="#000000"> 默认地,抛出异常导致一个fatal error。这意味着使用异常的类内建有安全机制。而仅仅使用一个错误标记,不能拥有这样的功能。处理错误标记失败只会你的脚本使用错误的值来继续执行。 </font><div>