PHP:异常与错误? [英] PHP: exceptions vs errors?

查看:86
本文介绍了PHP:异常与错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我在PHP手册中的某个地方缺少它,但错误和异常之间的区别究竟是什么呢?我唯一可以看到的区别是错误和异常的处理方式不同。但是什么导致异常,导致错误?

Maybe I'm missing it somewhere in the PHP manual, but what exactly is the difference between an error and an exception? The only difference that I can see is that errors and exceptions are handled differently. But what causes an exception and what causes an error?

推荐答案

异常是抛出 - 它们被捕获。错误通常是不可恢复的。比方说,你有一个代码块,将一行插入一个数据库。可能这个调用失败(重复的ID) - 你会想要一个错误,在这种情况下是一个异常。当您插入这些行时,您可以执行此操作

Exceptions are thrown - they are intended to be caught. Errors are generally unrecoverable. Lets say for instance - you have a block of code that will insert a row into a database. It is possible that this call fails (duplicate ID) - you will want to have a "Error" which in this case is an "Exception". When you are inserting these rows, you can do something like this

try {
  $row->insert();
  $inserted = true;
} catch (Exception $e) {
  echo "There was an error inserting the row - ".$e->getMessage();
  $inserted = false;
}

echo "Some more stuff";

程序执行将继续 - 因为您被捕获了异常。除非被捕获,否则将被视为错误。它将允许您在失败后继续执行程序。

Program execution will continue - because you 'caught' the exception. An exception will be treated as an error unless it is caught. It will allow you to continue program execution after it fails as well.

这篇关于PHP:异常与错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆