問題描述
我在 PHP 的 Zend 框架中為我的應用程序編寫了許多小型庫(一堆類).我也一直在庫的方法本身中捕獲這些異常并將它們記錄到文件中.
I had been writing number of small libraries (bunch of classes) for my application inside PHP's Zend Framework. I had also been catching these exceptions inside the library's methods itself and logging them to a file.
然后突然我遇到了一個問題,即使用這些庫的主應用程序即使在我預計它們會因致命錯誤而退出的情況下也不會因錯誤而退出.這樣做的問題是下面的代碼一直執行到最后——它不應該有.
Then suddenly I ran to an issue that my main application that was using these libraries would not quit due to errors even in situations I expected them to quit due to a fatal error. The problem with this was the code below kept executing till the end - which it should not have.
捕獲并記錄庫類中的大多數錯誤(特殊情況除外)似乎不是一個好習慣.他們應該總是按原樣拋出錯誤?這是一個正確的假設嗎?
It seems like its not a good practice to catch and perhaps log majority (except in special cases) of the errors inside the library classes. They should always throw the error as it is? Would that be a correct assumption?
如果有人能為我回答這個問題,我將不勝感激.
I'd appreciate if anyone could answer this for me.
推薦答案
在任何語言中,異常的一般哲學是它們傳達異常情況.您應該相應地使用它們.
The general philosophy of exceptions, in any language, is that they communicate exceptional circumstances. You should use them accordingly.
如果你最終用一個 try
塊來包圍每個函數調用,那就有問題了.異常被精確地設計為使錯誤處理合乎邏輯,并且不需要程序員跟蹤所有可能的錯誤路徑.因此,您應該在可以有意義地對異常做出響應的那些點捕獲異常.
If you end up surrounding every function call with a try
block, something is wrong. Exceptions are precisely designed to make error handling logical and not require the programmer to track all possible error paths. Therefore, you should catch exceptions precisely at those points where you can respond meaningfully to them.
如果您想不出比中止和傳播錯誤更好的方法,那么捕獲異常就沒有意義了.另一方面,如果您能夠對某些錯誤做出明智的反應,請抓住它們,然后重新拋出任何其他錯誤.
If you cannot think of anything better to do than to abort and propagate the error, then there's no point catching an exception. On the other hand, if there are some errors to which you can react sensibly, catch those, and rethrow anything else.
一個典型的例子是,如果您要處理大量文件.如果解析邏輯中的任何地方出現錯誤,您就無能為力,即使解析可能會中斷許多函數調用.但是,在主循環中,您可以嘗試
解析每個文件,如果有異常,您可以捕獲該異常,跳過該文件并繼續下一個.
A typical example is if you're processing lots of files. If there's an error anywhere inside the parsing logic, there's nothing you can do, even though parsing may go down many function calls. However, at the main loop you can try
parsing each file, and if there's an exception, you catch that, skip the file and continue with the next one.
如果您正在編寫一個庫函數,您可能希望在整個函數周圍有一個最后的 try 塊;不過,這在某種程度上取決于您.只需清楚地記錄用戶必須從您的庫中獲得哪些例外.
If you're writing a library function, you might want to have one final try block surrounding your entire function; that's somewhat up to you, though. Just document cleanly which exceptions the user has to expect from your library.
這篇關于異常捕獲:什么時候不捕獲它們?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!