Home  >  Article  >  Backend Development  >  PHP中try{}catch{}的具体用法详解_PHP教程

PHP中try{}catch{}的具体用法详解_PHP教程

WBOY
WBOYOriginal
2016-07-15 13:32:17976browse

try
{ //...}
catch(Exception $e)
{ //...}

PHP中try{}catch{}是异常处理.

将要执行的代码放入TRY块中,如果这些代码执行过程中某一条语句发生异常,则程序直接跳转到CATCH块中,由$e收集错误信息和显示.

PHP中try{}catch{}语句

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

  1.  ?php   
  2. try {   
  3. $mgr = new CommandManager();   
  4. $cmd = $mgr->getCommandObject("realcommand");   
  5. $cmd->execute();   
  6. } catch (Exception $e) {   
  7. print $e->getMessage();   
  8. exit();   
  9. }   
  10. ?>   

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

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

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


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446159.htmlTechArticle在 try { //...} catch(Exception $e) { //...} PHP中try{}catch{}是异常处理. 将要执行的代码放入TRY块中,如果这些代码执行过程中某一条语句发生异常,则...
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