問題描述
我一直想知道為什么要在我的 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模板網!