• <legend id='PLLpz'><style id='PLLpz'><dir id='PLLpz'><q id='PLLpz'></q></dir></style></legend>
    <tfoot id='PLLpz'></tfoot>

      <i id='PLLpz'><tr id='PLLpz'><dt id='PLLpz'><q id='PLLpz'><span id='PLLpz'><b id='PLLpz'><form id='PLLpz'><ins id='PLLpz'></ins><ul id='PLLpz'></ul><sub id='PLLpz'></sub></form><legend id='PLLpz'></legend><bdo id='PLLpz'><pre id='PLLpz'><center id='PLLpz'></center></pre></bdo></b><th id='PLLpz'></th></span></q></dt></tr></i><div id='PLLpz'><tfoot id='PLLpz'></tfoot><dl id='PLLpz'><fieldset id='PLLpz'></fieldset></dl></div>

    1. <small id='PLLpz'></small><noframes id='PLLpz'>

          <bdo id='PLLpz'></bdo><ul id='PLLpz'></ul>

        为什么以及如何在此示例 PHP 代码中使用异常?

        时间:2023-09-21

        <small id='XQkCK'></small><noframes id='XQkCK'>

        • <tfoot id='XQkCK'></tfoot>

            1. <legend id='XQkCK'><style id='XQkCK'><dir id='XQkCK'><q id='XQkCK'></q></dir></style></legend>
              • <bdo id='XQkCK'></bdo><ul id='XQkCK'></ul>
                  <tbody id='XQkCK'></tbody>

                <i id='XQkCK'><tr id='XQkCK'><dt id='XQkCK'><q id='XQkCK'><span id='XQkCK'><b id='XQkCK'><form id='XQkCK'><ins id='XQkCK'></ins><ul id='XQkCK'></ul><sub id='XQkCK'></sub></form><legend id='XQkCK'></legend><bdo id='XQkCK'><pre id='XQkCK'><center id='XQkCK'></center></pre></bdo></b><th id='XQkCK'></th></span></q></dt></tr></i><div id='XQkCK'><tfoot id='XQkCK'></tfoot><dl id='XQkCK'><fieldset id='XQkCK'></fieldset></dl></div>

                  本文介绍了为什么以及如何在此示例 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 代码中使用异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

                  上一篇:在生产服务器上抑制 php 错误的最佳方法 下一篇:如何在 PHP 中捕获 require() 或 include() 的错误?

                  相关文章

                  最新文章

                  <tfoot id='6H7IM'></tfoot>

                • <small id='6H7IM'></small><noframes id='6H7IM'>

                  • <bdo id='6H7IM'></bdo><ul id='6H7IM'></ul>

                    <legend id='6H7IM'><style id='6H7IM'><dir id='6H7IM'><q id='6H7IM'></q></dir></style></legend>

                      <i id='6H7IM'><tr id='6H7IM'><dt id='6H7IM'><q id='6H7IM'><span id='6H7IM'><b id='6H7IM'><form id='6H7IM'><ins id='6H7IM'></ins><ul id='6H7IM'></ul><sub id='6H7IM'></sub></form><legend id='6H7IM'></legend><bdo id='6H7IM'><pre id='6H7IM'><center id='6H7IM'></center></pre></bdo></b><th id='6H7IM'></th></span></q></dt></tr></i><div id='6H7IM'><tfoot id='6H7IM'></tfoot><dl id='6H7IM'><fieldset id='6H7IM'></fieldset></dl></div>