异常和错误之间的区别? [英] Difference between exceptions and errors?

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

问题描述

错误和异常有什么区别?

What is the difference between an error and an exception?

我已经在线阅读了许多资料,还有几本书,但提供的解释不是非常彻底。因此,我仍然感到困惑。

I have read numerous resources online and in a couple of books, but the explanations provided are not very thorough. As such, I am still confused.

谢谢!

编辑:
看起来像我问两个可能令人困惑的问题。我想要回答的主要问题是错误和异常之间的差异。所以,我已经编辑了更具体的一些。感谢大家的答案。

It looks like I asked two questions which was probably confusing. The main question that I wanted an answer to is the difference between errors and exceptions. So, I have edited the above to be more specific. Thanks everybody for your answers.

推荐答案

没有应该或最好的方式来做错误处理。

There is no "should" or "best" way to do error handling.

一般来说,有两种类型的错误

Generally speaking, there are two types of errors


  1. 处理的由程序的其他部分。用户永远不会看到或了解这些错误,至少不是直接的方式。

  2. 那些造成足够的失败的用户需要被通知。

请注意,这两者都与您用于处理错误的特定PHP机制无关。

Notice that neither of these have anything to do with the specific PHP mechanisms you'd use to handle errors.

如果您使用例外...
那么我建议全局使用异常 注册一个异常处理程序,让它做大部分的工作 - 包括其他PHP错误。无效的登录详细信息?

If you use exceptions... Then I recommend using exceptions across the board. Register an exception handler and let it do most of the work - including other PHP errors. Invalid login details?

class InvalidLoginException extends Exception
{
  protected $message = 'Login information is incorrect. Please try again.';
}

然后你有一堆实现选择。

Then you have a bunch of choices for implementation.

try {
  $user->login(); // will throw and InvalidLoginException if invalid
}
catch ( InvalidLoginException $e )
{
  // display an error message
}

或者,如果你这样选择,让异常处理程序做到这一点。也许在更灵活的方式

Or, if you so choose, let the exception handler do it. Maybe even in a more flexible way

class ApplicationErrorException extends Exception{}
class InvalidLoginException extends ApplicationErrorException 
{
  protected $message = 'Login information is incorrect. Please try again.';
}

然后,在异常处理程序中

Then, in the exception handler

if ( $exception instanceof ApplicationErrorException )
{
  // dislpay error message
}

但异常不是唯一的方法,而一些人甚至不认为是一个好方法

But exceptions aren't the only way, and by some not even considered a good way.

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

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