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 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧