php 异常处理有什么用?-php教程

资源魔 39 0

异样解决(Exception)用于正在指定的谬误发作时扭转剧本的失常流程。当异样被抛出时,厥后的代码没有会持续执行,PHP会测验考试查找婚配的“catch”代码块。

异样(Exception)用于正在指定的谬误发作时扭转剧本的失常流程。

异样的根本应用

当异样被抛出时,厥后的代码没有会持续执行,PHP 会测验考试查找婚配的 "catch" 代码块。

假如异样不被捕捉,并且又没用应用 set_exception_handler() 作相应的解决的话,那末将发作一个重大的谬误(致命谬误),而且输入 "Uncaught Exception" (未捕捉异样)的谬误音讯。

让咱们测验考试抛出一个异样,同时没有去捕捉它:

<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
 {
 throw new Exception("Value must be 1 or below");
 }
return true;
}
//trigger exception
checkNum(2);
?>

下面的代码会取得相似这样的一个谬误:

Fatal error: Uncaught exception 'Exception' 
with message 'Value must be 1 or below' in C:\webfolder\test.php:6 
Stack trace: #0 C:\webfolder\test.php(12): 
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

Try, throw 以及 catch

要防止下面例子呈现的谬误,咱们需求创立适当的代码来解决异样。

正确的解决顺序该当包罗:

Try - 应用异样的函数应该位于 "try" 代码块内。假如不触发异样,则代码将照常持续执行。然而假如异样被触发,会抛出一个异样。Throw - 这里规则若何触发异样。每个 "throw" 必需对应至多一个 "catch"Catch - "catch" 代码块会捕捉异样,并创立一个蕴含异样信息的工具

让咱们触发一个异样:

<?php
//创立可抛出一个异样的函数
function checkNum($number)
{
if($number>1)
 {
 throw new Exception("Value must be 1 or below");
 }
return true;
}
//正在 "try" 代码块中触发异样
try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//捕捉异样
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>

下面代码将取得相似这样一个谬误:

Message: Value must be 1 or below

例子诠释:

下面的代码抛出了一个异样,并捕捉了它:

创立 checkNum() 函数。它检测数字能否年夜于 1。假如是,则抛出一个异样。正在 "try" 代码块中挪用 checkNum() 函数。checkNum() 函数中的异样被抛出"catch" 代码块接纳到该异样,并创立一个蕴含异样信息的工具 ($e)。经过从这个 exception 工具挪用 $e->getMessage(),输入来自该异样的谬误音讯

不外,为了遵照“每一个 throw 必需对应一个 catch”的准则,能够设置一个顶层的异样解决器来解决漏掉的谬误。

保举教程:《php教程》

以上就是php 异样解决有甚么用?的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学 异常处理

抱歉,评论功能暂时关闭!