SPL 提供了一系列标准异常。日常的使用中我们应该根据需求科学的使用它们,来使我们的程序更加健壮。LogicException 是从 Exception 基类派生的,没有添加任何附加方法。抛出逻辑异常和抛出标准一次的方法类似,区别在于逻辑异常须在应用程序编写有误时才抛出。下面演示下LogicException类的使用。
<span>class</span><span> App { </span><span>protected</span> $_loaded = <span>false</span><span>; </span><span>protected</span><span> $_name; </span><span>public</span><span> function start() { $</span><span>this</span>->_loaded = <span>true</span><span>; $</span><span>this</span>->_name = <span>'</span><span>unzin</span><span>'</span><span>; } </span><span>public</span><span> function GetName() { </span><span>if</span>(!$<span>this</span>-><span>_loaded) { </span><span>throw</span> <span>new</span> LogicException(<span>"</span><span>Error Processing Request</span><span>"</span>, <span>1</span><span>); } </span><span>return</span> $<span>this</span>-><span>_name; } } </span><span>try</span><span> { $APP </span>= <span>new</span><span> App(); echo $APP </span>-><span> GetName(); } </span><span>catch</span><span>(LogicException $e) { echo $e</span>-><span>getMessage(); }</span>