当前位置:首页 > PHP教程 > php应用 > 列表

php 异常处理有什么用?

发布:smiling 来源: PHP粉丝网  添加日期:2022-07-03 09:03:35 浏览: 评论:0 

异常处理(Exception)用于在指定的错误发生时改变脚本的正常流程。当异常被抛出时,其后的代码不会继续执行,PHP会尝试查找匹配的“catch”代码块。

异常(Exception)用于在指定的错误发生时改变脚本的正常流程。

异常的基本使用

当异常被抛出时,其后的代码不会继续执行,PHP 会尝试查找匹配的 "catch" 代码块。

如果异常没有被捕获,而且又没用使用 set_exception_handler() 作相应的处理的话,那么将发生一个严重的错误(致命错误),并且输出 "Uncaught Exception" (未捕获异常)的错误消息。

让我们尝试抛出一个异常,同时不去捕获它:

  1. <?php 
  2.  
  3. //create function with an exception 
  4.  
  5. function checkNum($number) 
  6.  
  7. { 
  8.  
  9. if($number>1) 
  10.  
  11.  { 
  12.  
  13.  throw new Exception("Value must be 1 or below"); 
  14.  
  15.  } 
  16.  
  17. return true; 
  18.  
  19. } 
  20.  
  21. //trigger exception 
  22.  
  23. checkNum(2); 
  24.  
  25. ?> 

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

Fatal error: Uncaught exception 'Exception'

with message 'Value must be 1 or below' in C:\webfolder\test.php:6

Stack trace: #0 C:\webfolder\test.php(12):

checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

Try, throw 和 catch

要避免上面例子出现的错误,我们需要创建适当的代码来处理异常。

正确的处理程序应当包括:

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

让我们触发一个异常:

  1. <?php 
  2.  
  3. //创建可抛出一个异常的函数 
  4.  
  5. function checkNum($number) 
  6.  
  7. { 
  8.  
  9. if($number>1) 
  10.  
  11.  { 
  12.  
  13.  throw new Exception("Value must be 1 or below"); 
  14.  
  15.  } 
  16.  
  17. return true; 
  18.  
  19. } 
  20.  
  21. //在 "try" 代码块中触发异常 
  22.  
  23. try 
  24.  
  25. { 
  26.  
  27. checkNum(2); 
  28.  
  29. //If the exception is thrown, this text will not be shown 
  30.  
  31. echo 'If you see this, the number is 1 or below'; 
  32.  
  33. } 
  34.  
  35. //捕获异常 
  36.  
  37. catch(Exception $e) 
  38.  
  39. { 
  40.  
  41. echo 'Message: ' .$e->getMessage(); 
  42.  
  43. } 
  44.  
  45. ?> 

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

Message: Value must be 1 or below

例子解释:

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

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

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

Tags: php异常处理

分享到: