为什么以及如何在此示例PHP代码中使用异常? [英] Why and how would you use Exceptions in this sample PHP code?

查看:80
本文介绍了为什么以及如何在此示例PHP代码中使用异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想,为什么要在PHP中使用异常。让我们来看一个简单的例子:

I've been wondering why would I use Exceptions in my PHP. Let's take a look at a simple example:

class Worker
{
 public function goToWork()
 {
  return $isInThatMood ?
  // Okay, I'll do it.
  true : 
  // In your dreams...
  false;
 }
}

$worker = new Worker;
if (!$worker->goToWork())
{
 if (date('l',time()) == 'Sunday')
  echo "Fine, you don't have to work on Sundays...";
 else
  echo "Get your a** back to work!";
}
else
 echo "Good.";

我有理由使用异常代码吗?为什么?代码如何构建?

Is there a reason for me to use Exceptions for that kind of code? Why? How would the code be built?

代码可能会产生错误:

class FileOutputter
{
 public function outputFile($file)
 {
  if (!file_exists($file))
   return false;
  return file_get_contents($file);
 }
}

为什么在上述情况下会使用异常?我有一种感觉,异常可以帮助您识别问题的类型,这是真的吗?

Why would I use Exceptions in the above case? I have a feeling that Exceptions help you to recognize the type of the problem, which occured, true?

所以,我在这段代码中适当地使用了异常:

So, am I using Exceptions appropriately in this code:

class FileOutputter
{
 public function outputFile($file)
 {
  if (!file_exists($file))
   return throw new Exception("File not found.",123);
  try
  {
   $contents = file_get_contents($file);
  }
  catch (Exception $e)
  {
   return $e;
  }
  return $contents;
 }
}

还是那个穷人?现在底层代码可以这样做:

Or is that poor? Now the underlying code can do this:

$fo = new FileOutputter;
try
{
 $fo->outputFile("File.extension");
}
catch (Exception $e)
{
 // Something happened, we could either display the error/problem directly
 echo $e->getMessage();
 // Or use the info to make alternative execution flows
 if ($e->getCode() == 123) // The one we specified earlier
  // Do something else now, create "an exception"
}

或者我完全迷失在这里? >

Or am I completely lost here?

推荐答案

什么时候应该使用异常?



您使用异常来表示特殊条件;也就是说,阻止一种方法履行合同的东西,而不应该在该级别发生。

When should I use an exception?

You use an exception to indicate an exceptional condition; that is, something which prevents a method from fulfilling its contract, and which shouldn't have occurred at that level.

例如,你可能有一个方法, Record :: save(),将对记录的更改保存到数据库中。如果由于某些原因,这不能完成(例如,数据库错误发生或数据约束被破坏),那么您可以抛出异常来指示失败。

For example, you might have a method, Record::save(), which saves changes to a record into a database. If, for some reason, this can't be done (e.g. a database error occurs, or a data constraint is broken), then you could throw an exception to indicate failure.

异常通常被命名,以便它们表示错误的性质,例如 DatabaseException 。您可以将 Exception 子类化,以此方式创建自定义的异常,例如

Exceptions are usually named such that they indicate the nature of the error, for example, DatabaseException. You can subclass Exception to create custom-named exceptions in this manner, e.g.

class DatabaseException extends Exception {}

(当然,你可以利用继承来给出例外的一些其他诊断信息,例如连接细节或数据库错误代码。)

(Of course, you could take advantage of inheritance to give this exception some additional diagnostic information, such as connection details or a database error code, for example.)

再考虑一个例子;一种检查文件存在的方法。如果该文件不存在,那么应该可能引发异常,因为该方法的目的是执行所述检查。然而,打开文件并执行某些处理的方法可能会引发异常,因为该文件应该存在等。

Consider a further example; a method which checks for file existence. This should probably not throw an exception if the file doesn't exist, since the purpose of the method was to perform said check. However, a method which opens a file and performs some processing could throw an exception, since the file was expected to exist, etc.

最初当事情不是特殊的时候,并不总是清楚的。像大多数事情一样,经验会教你一次,当你应该也不应该抛出异常。

Initially, it's not always clear when something is and isn't exceptional. Like most things, experience will teach you, over time, when you should and shouldn't throw an exception.

有关异常的有用的东西是它们立即跳出当前的方法,并调出堆栈,直到被捕获和处理,这意味着你可以移动错误 - 处理逻辑更高,虽然理想上并不太高。

The useful thing about exceptions is that they immediately leap out of the current method and head up the call stack until they're caught and handled, which means you can move error-handling logic higher up, although ideally, not too high.

通过使用一个清晰​​的机制来处理故障情况,当一些坏的情况下,你会自动启动错误处理代码发生,这意味着你可以避免处理各种必须检查的魔法哨兵值,或者更糟的是,一个全局错误标志来区分一系列不同的可能性。

By using a clear mechanism to deal with failure cases, you automatically kick off the error handling code when something bad happens, which means you can avoid dealing with all sorts of magic sentinel values which have to be checked, or worse, a global error flag to distinguish between a bunch of different possibilities.

这篇关于为什么以及如何在此示例PHP代码中使用异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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