dopod0901 2019-03-25 12:46
浏览 88
已采纳

故意不抓异常

So I have this little bit of code

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;

Up until now, I would have done something like

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

The difference being, that I could catch the Exception if I want to, while that's not possible with the exit statement.

However, in this case I do want my program to exit. But my IDE warns me that I'm not catching Exceptions. So, should I really do this now:

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

The latter appears to me as unecessary and actually decreasing code quality. So: Is it acceptable to deliberately NOT catch some exceptions? Or should I even get rid of the exception alltogether and just use plain old exit?

I tried searching for this question, but I only got results about people who had technical problems with try/catch not working.

  • 写回答

1条回答

  • duananyantan04633 2019-03-25 12:50
    关注

    No, you should not catch your exception there if you do not want to.

    Even if you want to catch it, it could very easily be somewhere else, so you definitely do not have to wrap this in a try-catch.

    Instead, you should tell your IDE that this method is supposed to throw an exception:

    /**
     * @throws \Exception
     */
    public function getPrices($debtorId)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误