【问题标题】:Is there a technical reason not to use try catch for retrieving properties that may not be set [closed]是否有技术原因不使用 try catch 来检索可能未设置的属性 [关闭]
【发布时间】:2020-02-20 21:54:11
【问题描述】:

抛出错误而不是检查是否设置了变量是否会造成很大的性能损失。

例如。 尝试捕获

public function getProperty(): int
{
    try {
        return $this->getDetail('some-detail');
    } catch (Exception $e) {
        return 0;
    }
}

或者用isset

public function getProperty(): int
{    
    return isset($this->getDetail('some-detail')) ? $this->getDetail('some-detail') ? 0;
    // or even $this->getDetail('some-detail') ?? 0; in php7
}

【问题讨论】:

    标签: php


    【解决方案1】:

    这两个选项实际上都不会以预期的方式工作(我假设是发送一个默认值,以防该值设置不正确)。

    如果$this->getDetail不返回整数,下面的代码仍然会抛出错误

    public function getProperty(): int
    {    
        return $this->getDetail('some-detail') ??  0; // PHP prior to 7 did not support return type hints 
    }
    

    以下代码将捕获getDetail 引发的任何异常,但如果由于: int 部分而导致结果不是整数,则仍然会失败。

    public function getProperty(): int
    {
        try {
            return $this->getDetail('some-detail');
        } catch (Exception $e) {
            return 0;
        }
    }
    

    实际可行且可以讨论的方式是:

    捕捉你期望的正确错误

    public function getProperty(): int
    {
        try {
            return $this->getDetail('some-detail');
        } catch (TypeError $e) {
            return 0;
        } 
    }
    

    检查是否即将返回正确的返回类型:

    public function getProperty(): int
    {
        $value = $this->getDetail('some-detail');
        return is_int($value) ? $value : 0;
    }
    

    请注意,异常处理在触发时运行起来确实较慢,但不触发异常的代码(应该是大部分)运行速度一样快,无论它是在 try catch 块内还是外。 (SourceSource

    我个人认为这正是应该使用异常处理的情况:它是由异常情况引起的,这种情况很少见(我希望如此),我们有办法从中恢复,而不会使整个请求停止。

    【讨论】:

      【解决方案2】:

      如果程序的逻辑旨在确保该变量必须存在并且没有它就无法进一步执行程序,那么抛出异常而不是检查变量的存在是有意义的。或者,高于调用堆栈的级别,必须返回异常,以便正确处理事件。例如,如果我们想通知用户一个问题。无论如何,这是一个架构问题。

      【讨论】:

      • 是的,如果要使用异常,那对我来说也是有意义的,但在这种情况下不是。在这种情况下用于返回默认值。
      猜你喜欢
      • 1970-01-01
      • 2017-04-03
      • 2011-07-03
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 2011-06-10
      • 1970-01-01
      • 2018-03-20
      相关资源
      最近更新 更多