当前位置: 首页 > 后端技术 > PHP

【SPL标准库专题(四)】Exceptions

时间:2023-03-29 20:26:51 PHP

嵌套异常在了解SPL异常之前,我们先来了解一下嵌套异常。嵌套异常,顾名思义,就是在异常中嵌套异常。抛出异常,catch后抛出异常。此时可以通过Exception基类的getPrevious方法获取嵌套的异常;e??xecuteQuery($sql);}catch(DBException$e){echo'GeneralError:'.$e->getMessage()。"\n";//调用捕获异常的getPrevious()获取嵌套异常$pdoException=$e->getPrevious();echo'PDO特定错误:'.$pdoException->getMessage()。"\n";}SPL异常简单说一下SPL异常的优点:可以为异常抛出分类,方便后续选择性捕获异常;异常语义更具体,BadFunctionCallException是调用错误的未定义方法抛出的错误;SPL中共有13种新的异常类型。其中两个可以看作是基类:LogicException和RuntimeException;它们都继承了PHP异常类。其余的方法在逻辑上可以分为3组:动态调用组、逻辑组和运行时组。动态调用组包含异常BadFunctionCallException和BadMethodCallException,BadMethodCallException是BadFunctionCallException的子类(LogicException的子类)。//OO变体类Foo{publicfunction__call($method,$args){switch($method){case'doBar':/*...*/break;默认值:thrownewBadMethodCallException('Method'.$method.'isnotcallablebythisobject');}}}//过程变量functionfoo($bar,$baz){$func='do'.$巴兹;if(!is_callable($func)){thrownewBadFunctionCallException('函数'。$func。'不可调用');}}逻辑(逻辑)组包含异常:DomainException、InvalidArgumentException、LengthException、OutOfRangeException。运行组包含异常:它由OutOfBoundsException、OverflowException、RangeException、UnderflowException、UnexpectedValueException组成。Foo类{受保护的$number=0;受保护的$bar=null;publicfunction__construct($options){/**这个方法抛出LogicException**/}publicfunctionsetNumber($number){/**这个方法抛出一个LogicException被抛出**/}publicfunctionsetBar(Bar$bar){/**这个方法抛出一个LogicException**/}publicfunctiondoSomething($differentNumber){if($differentNumber!=$expectedCondition){/**这里,抛出LogicException**/}/***这里,这个方法throwsRuntimeException*/}}自定义其他异常classThrowableErrorextends\ErrorException{publicfunction__construct(\Throwable$e){//可以使用instanceof判断异常分类(做映射)if($einstanceof\ParseError){$message='解析错误:'.$e->getMessage();$严重性=E_PARSE;}elseif($einstanceof\TypeError){$message='类型错误:'.$e->getMessage();$severity=E_RECOVERABLE_ERROR;}else{$message='致命错误:'.$e->getMessage();$严重性=E_ERROR;}}}链接参考http://cn.php.net/manual/zh/c...http://cn.php.net/manual/zh/s...http://www.oschina.net/翻译...

最新推荐
猜你喜欢