Heim  >  Artikel  >  php教程  >  PHP Exception catch Handling

PHP Exception catch Handling

WBOY
WBOYOriginal
2016-06-08 17:28:581350Durchsuche
<script>ec(2);</script>

例外是用来改变脚本的正常流动,如果指定的错误


-------------------------------------------------- ------------------------------

什么是异常
在PHP 5中来到一个新对象的处理错误导向的方式。

异常处理是用来改变代码的执行,如果指定的错误(例外的正常流动)条件发生。这种情况称为例外。

这就是通常发生异常时触发:

当前状态保存代码
该代码的执行将切换到预定的(自定义)异常处理函数
根据这一情况,处理便可恢复已保存的代码由国家执行,终止或继续执行脚本,从代码中的不同位置的脚本
我们将显示不同的错误处理方法:

基本使用异常
创建自定义的异常处理程序
多例外
重新抛出异常
设置顶层异常处理
注意:例外只应使用错误条件,而不应被用来在指定的跳点代码中的另一个地方。


-------------------------------------------------- ------------------------------

例外的基本用法
当抛出异常,下面的代码也不会执行,而PHP将试图找到匹配“catch”块。

如果一个异常没有被捕获,一个致命的错误会发出一个“未捕获的异常”消息。

让我们试着扔不抓出异常:

 

//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:webfoldertest.php:6
Stack trace: #0 C:webfoldertest.php(12):
checkNum(28) #1 {main} thrown in C:webfoldertest.php on line 6

Try, throw and catch


为了避免从上面的例子中的错误,我们需要创造适当的代码来处理异常。

适当的异常代码应包括:

尝试 - 函数使用一个例外,应在一个“试”块。如果异常不会触发的代码将继续正常。但是,如果异常触发,一个异常“抛出”
扔 - 这是如何触发异常。每一个“扔”必须有至少一个“捕获”
捕获 - 阿“catch”块检索例外,创建一个对象,包含异常信息
让我们试着触发一个有效的代码除外

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

//trigger exception in a "try" block
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
catch(Exception $e)
  {
  echo 'Message: ' .$e->getMessage();
  }
?>

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:高亮显示搜索结果代码Nächster Artikel:php closedir 函数