PHP 异常处理(2)
来源:未知 责任编辑:责任编辑 发表时间:2014-01-06 18:18 点击:次
	   
	Try, throw 和 catch
要避免上面例子出现的错误,我们需要创建适当的代码来处理异常。
处理处理程序应当包括:
- Try - 使用异常的函数应该位于 "try" 代码块内。如果没有触发异常,则代码将照常继续执行。但是如果异常被触发,会抛出一个异常。
- Throw - 这里规定如何触发异常。每一个 "throw" 必须对应至少一个 "catch"
- 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();
 }
?>
	上面代码将获得类似这样一个错误:
相关新闻>>
- 发表评论
- 
				
- 最新评论 进入详细评论页>>





![smarty局部缓存技术[源码分析]](/uploads/allimg/130827/11214T939-0-lp.jpg)