📜  php try-catch

📅  最后修改于: 2020-09-30 03:16:57             🧑  作者: Mango

PHP尝试捕获

PHPtryandcatch是具有异常处理功能的块,其中包含处理异常的代码。它们在异常处理中起重要作用。try-catch块中有一个更重要的关键字是throw。throw是用于引发异常的关键字。

每个try块必须至少有一个catch块。另一方面,try块也可以具有多个catch块来处理各种异常。

句法

在异常处理中使用以下语法来处理运行时错误-


让我们详细了解try-throw-catch:

Try

try块包含可能包含异常的代码。catch块会捕获运行时在try块中引发的异常。因此,每个try块必须至少具有一个catch块。它由其中可能发生异常的代码块组成。

关于尝试,需要注意以下几点:

  • 在try块之后必须是catch或finally块。
  • 一个try块必须至少有一个catch块。
  • 一个try块可以有多个catch块。

Catch

catch块捕获try块中引发的异常。它包含捕获异常的代码,该异常由try块中的throw关键字引发。当引发特定异常时,将执行catch块。PHP查找匹配的catch块,并将异常对象分配给变量。

关于渔获要注意的以下几点:

  • 可以尝试多个捕获块。
  • 引发的异常由一个或多个catch捕获并解决。
  • catch块始终与try块一起使用。不能单独使用。
  • 它在try块之后。

Throw

它是一个关键字,用于引发异常。请注意,至少一个抛出有一个“捕获块”来捕获异常。

它列出了函数抛出的异常,而函数本身无法处理这些异常。

Final

它是一个块,其中包含要执行的程序的基本代码。finally块还用于PHP中的清理活动。它类似于catch块,用于处理异常。唯一的区别是,无论是否处理异常,它始终执行。

可以在catch块之后或代替catch块来指定finally块。无论是否引发异常,它总是在try和catch块之后且在正常执行重新开始之前执行。在以下情况下很有用-关闭数据库连接,流。

例子1

让我们以一个示例来说明throw和try-catch以及finally块的常见流程:

=1) {
     //throw an exception
     throw new Exception("Value must be less than 1");
   }
   return true;
}

//trigger an exception in a "try" block
try {
   checkNumber(5);
   //If the exception throws, below text will not be display
   echo 'If you see this text, the passed value is less than 1';
}

//catch exception
catch (Exception $e) {
   echo 'Exception Message: ' .$e->getMessage();
}
finally {
   echo '
It is finally block, which always executes.'; } ?>

输出:

Exception Message: Value must be less than 1
It is finally block, which always executes.

例子2

  If you see this text, the passed value is an EVEN Number ';
     }
     //catch exception
     catch (Exception $e) {
         echo '
Exception Message: ' .$e->getMessage() .''; } finally { echo '
It is finally block, which always executes.'; } } echo 'Output for ODD Number'; testEven(19); echo '

'; echo 'Output for EVEN Number'; testEven(12); ?>

输出:

在下面的输出中,您可以看到当传递奇数时,将显示异常消息。另一方面,当传递偶数时,将显示另一条消息。

Output for ODD Number 
Exception Message: Passed number is an ODD Number
It is finally block, which always executes.

Output for EVEN Number
If you see this text, the passed value is an EVEN Number
It is finally block, which always executes.

示例2:自定义异常和多重捕获语句

在下面的示例中,我们将创建一个扩展Exception类的自定义异常类。在这里,我们还将使用多个catch块和一个try块。

  If you see this text, the passed value is an EVEN Number ';
     }
     
     //catch exception
     catch (OddNumberException $ex) {
         echo '
Exception Message: ODD Number' .''; } //catch exception catch (Exception $e) { echo '
Exception Message: ' .$e->getMessage() .''; } } echo 'Output for EVEN Number'; testEven(28); echo '

'; echo 'Output for ODD Number'; testEven(17); ?>

输出:

Output for EVEN Number
If you see this text, the passed value is an EVEN Number 

Output for ODD Number 
Exception Message: ODD Number

重要事项:

  • 除了PHP异常类及其子类,我们还可以创建自己的自定义异常类来处理uncatch异常。
  • 在PHP 5.5及更高版本中,finally块用于处理异常。无论是否抛出异常,总是要执行此块。