ホームページ  >  記事  >  バックエンド開発  >  PHPにおける例外処理とは何ですか?

PHPにおける例外処理とは何ですか?

王林
王林転載
2023-09-17 08:45:10926ブラウズ

PHPにおける例外処理とは何ですか?

#例外とは、プログラムの実行中に発生する問題です。プログラムの実行中に例外が発生すると、ステートメントに続くコードは実行されず、PHP は最初に一致する catch ブロックを見つけようとします。例外がキャッチされない場合は、PHP 致命的エラーが発行され、「Uncaught Exception」が表示されます。

文法

   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";
      }

中国語翻訳は次のとおりです:

<?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

To To例外を処理するには、プログラム コードを try ブロック内に配置する必要があります。各試行には少なくとも 1 つの対応する catch ブロックが必要です。複数の catch ブロックを使用して、さまざまなカテゴリの例外をキャッチできます。

以上がPHPにおける例外処理とは何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。