码迷,mamicode.com
首页 > Web开发 > 详细

PHP的Try, throw 和 catch

时间:2014-11-25 12:41:18      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   使用   sp   on   div   art   

PHP的Try, throw 和 catch  

 

 

Try, throw 和 catch

  1. Try - 使用异常的函数应该位于 "try" 代码块内。如果没有触发异常,则代码将照常继续执行。但是如果异常被触发,会抛出一个异常。
  2. Throw - 这里规定如何触发异常。每一个 "throw" 必须对应至少一个 "catch"
  3. Catch - "catch" 代码块会捕获异常,并创建一个包含异常信息的对象

让我们触发一个异常:

<?php 
//创建可抛出一个异常的函数
function checkNum($number)
{
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//在 "try" 代码块中触发异常
try {
checkNum(2);
//If the exception is thrown, this text will not be shown echo ‘If you see this, the number is 1 or below‘; }
//捕获异常
 catch(Exception $e)
{ echo ‘Message: ‘ .$e->getMessage(); }
?>

上面代码将获得类似这样一个错误:

Message: Value must be 1 or below 

例子解释:

上面的代码抛出了一个异常,并捕获了它:

  1. 创建 checkNum() 函数。它检测数字是否大于 1。如果是,则抛出一个异常。
  2. 在 "try" 代码块中调用 checkNum() 函数。
  3. checkNum() 函数中的异常被抛出
  4. "catch" 代码块接收到该异常,并创建一个包含异常信息的对象 ($e)。
  5. 通过从这个 exception 对象调用 $e->getMessage(),输出来自该异常的错误消息

不过,为了遵循“每个 throw 必须对应一个 catch”的原则,可以设置一个顶层的异常处理器来处理漏掉的错误。

PHP的Try, throw 和 catch

标签:style   blog   io   ar   使用   sp   on   div   art   

原文地址:http://www.cnblogs.com/richstorm/p/4120516.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!