首页 > PHP > 正确的使用PHP5中的异常处理

正确的使用PHP5中的异常处理

2009年4月16日

本来想自己写个具体的例子的, 但是太忙了, 又怕转头就忘了, 用的网上的代码.
应该明白的是PHP5中的异常处理和类是紧密结合在一起的, 在进行异常捕捉前对代码中可能出现的异常情况进行判断, 然后抛出异常.

<?php 
// PHP 5 
require_once('cmd_php5/Command.php'); 
class CommandManagerException extends Exception{} 
class IllegalCommandException extends Exception{} 
 
class CommandManager { 
    private $cmdDir = "cmd_php5"; 
 
    function __construct() { 
        if (!is_dir($this->cmdDir)) { 
            throw new CommandManagerException("directory error: $this->cmdDir"); 
        } 
    } 
 
    function getCommandObject($cmd) { 
        $path = "{$this->cmdDir}/{$cmd}.php"; 
        if (!file_exists($path)) { 
            throw new IllegalCommandException("Cannot find $path"); 
        } 
        require_once $path; 
        if (!class_exists($cmd)) { 
            throw new IllegalCommandException("class $cmd does not exist"); 
        } 
 
        $class = new ReflectionClass($cmd); 
        if (!$class->isSubclassOf(new ReflectionClass('Command'))) { 
            throw new IllegalCommandException("$cmd is not a Command"); 
        } 
        return $class->newInstance(); 
    } 
} 
?>

当我们的类不能找到正确的command目录时,将抛出一个CommandManagerException异常;当在生成Command对象时产生错误,则getCommandObject()方法将抛出一个IllegalCommandException异常。注意存在多个可能导致抛出IllegalCommandException异常的原因(如未找到文件,或在文件中未找到正确的类)。我们将前两个例子结合起来并为IllegalCommandException提供整型的错误标识常量来代表不同类型的出错原因。
现在CommandManager类已经具备了处理这多种出错情况的能力,我们可以增加新的catch语句来匹配不同的错误类型。
代码后半段

<?php 
// PHP 5 
try { 
    $mgr = new CommandManager(); 
    $cmd = $mgr->getCommandObject('realcommand'); 
    $cmd->execute(); 
} catch (CommandManagerException $e) { 
    die($e->getMessage()); 
} catch (IllegalCommandException $e) { 
    error_log($e->getMessage()); 
    print "attempting recovery\n"; 
    // perhaps attempt to invoke a default command? 
} catch (Exception $e) { 
    print "Unexpected exception\n"; 
    die($e->getMessage()); 
} 
?>

看了代码, 应该明白这里和c#直接try…catch不同的是多了个判断的过程. 为什么在C#中不需要, 很简单, C#底层中已经对这些代码进行封装过了.
来个c#打开串口的例子

            try
            {
                if (comPort.IsOpen) comPort.Close();
 
                comPort.BaudRate = int.Parse(_baudRate);
                comPort.DataBits = int.Parse(_dataBits);
                comPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), _stopBits);
                comPort.Parity = (Parity)Enum.Parse(typeof(Parity), _parity);
                comPort.PortName = _portName;
                comPort.Open();
                if (this.IsBatch)
                    DisplayData(MsgType.Normal, "当前模式:批量传输,正在接收数据..\n");
                else
                    DisplayData(MsgType.Normal, "当前模式:实时传输,正在接受数据..\n");
                return true;
            }
            catch (Exception ex)
            {
                //DisplayData(MsgType.Error, ex.Message);
                FormUtility.Alert(ex.Message);
                return false;
            }

以前对PHP5的异常处理机制了解的不够透彻, 按照C#的方法直接去了才发现还是有不同的. 呵呵, 学习了.

admin PHP

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.