Home  >  Article  >  php教程  >  PHP Try-catch 语句使用技巧,try-catch使用技巧

PHP Try-catch 语句使用技巧,try-catch使用技巧

WBOY
WBOYOriginal
2016-06-13 08:45:291180browse

PHP Try-catch 语句使用技巧,try-catch使用技巧

PHP Try-catch 语句
为了进一步处理异常,我们需要使用try-catch语句----包括Try语句和至少一个的catch语句。任何调用 可能抛出异常的方法的代码都应该使用try语句。Catch语句用来处理可能抛出的异常。以下显示了我们处理getCommandObject()抛出的异常的方法:

<&#63;php 
try { 
  $mgr = new CommandManager(); 
  $cmd = $mgr->getCommandObject("realcommand"); 
  $cmd->execute(); 
} catch (Exception $e) { 
  print $e->getMessage(); 
  exit(); 
} 
&#63;>

可以看到,通过结合使用throw关键字和try-catch语句,我们可以避免错误标记“污染”类方法返回的值。因为“异常”本身就是一种与其它任何对象不同的PHP内建的类型,不会产生混淆。

如果抛出了一个异常,try语句中的脚本将会停止执行,然后马上转向执行catch语句中的脚本。

如果异常抛出了却没有被捕捉到,就会产生一个fatal error。

您可能感兴趣的文章:

  • php Try Catch异常测试
  • php中try catch捕获异常实例详解
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn