首页  >  文章  >  后端开发  >  PHP中的异常处理是什么?

PHP中的异常处理是什么?

王林
王林转载
2023-09-17 08:45:10926浏览

PHP中的异常处理是什么?

异常是程序执行过程中出现的问题。在程序执行过程中,发生异常时,该语句后面的代码将不会被执行,PHP 将尝试查找第一个匹配的 catch 块。如果未捕获异常,则会发出 PHP 致命错误,并显示“未捕获异常”。

语法

   try {
      print "this is our try block";
      throw new Exception();
      }catch (Exception $e) {
         print "something went wrong, caught yah! n";
      }finally {
         print "this part is always executed";
      }

Example

的中文翻译为:

示例

<?php
   function printdata($data) {
      try {
         //If var is six then only if will be executed
         if($data == 6) {
         // If var is zero then only exception is thrown
         throw new Exception(&#39;Number is six.&#39;);
            echo "</p><p> After throw (It will never be executed)";
         }
      }
      // When Exception has been thrown by try block
         catch(Exception $e){
            echo "</p><p> Exception Caught", $e->getMessage();
         }
      //this block code will always executed.
         finally{
            echo "</p><p> Final block will be always executed";
         }
   }
   // Exception will not be rised here
      printdata(0);
      // Exception will be rised
      printdata(6);

?>

输出

Final block will be always executed
Exception CaughtNumber is six.
Final block will be always executed

注意

要处理异常,程序代码必须位于 try 块内。每次尝试必须至少有一个相应的 catch 块。多个catch块可用于捕获不同类别的异常。

以上是PHP中的异常处理是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除