簡體   English   中英

故意不捕獲異常

[英]Deliberately not catching Exceptions

所以我有一點點代碼

public function getPrices($debtorId)
{
    $priceListId = $this->getPriceListId($debtorId);
    if(!$priceListId){
        throw new \Exception('No list found for this customer');
    }

    // doing some operations here that require $priceListId

    return $prices;

到現在為止,我會做類似的事情

if(!$priceListId) exit('No list found for this customer');

區別在於, 如果我想可以捕獲Exception,而exit語句則無法實現。

但是,在這種情況下,我確實希望我的程序退出。 但是我的IDE警告我,我沒有捕捉到異常。 所以,我現在真的應該這樣做:

try {
    $prices = $priceHandler->getPrices($debtorId);
} catch(Exception $e) {
    exit($e->getMessage());
}

在我看來,后者似乎是不必要的,實際上降低了代碼質量。 因此: 故意不捕獲某些異常是否可以接受? 還是我應該完全擺脫異常,而只使用普通的舊exit

我嘗試搜索此問題,但僅獲得有關嘗試/捕獲無法正常工作的技術人員的結果。

不,如果您不願意,則不應在此處捕獲異常。

即使您想捕獲它,它也很可能位於其他地方,因此您絕對不必將其包裝在try-catch中。

相反,您應該告訴IDE該方法應該引發異常:

/**
 * @throws \Exception
 */
public function getPrices($debtorId)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM