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

查看:24
本文介绍了为什么以及如何在此示例 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?

还有可能产生错误的代码:

And what about code that may produce errors:

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天全站免登陆