在 php 中抛出新的 NullPointerException

throw new NullPointerException in php

我有一个问题:如何在 PHP 中抛出 NullPointer 类型的新异常?

我想做这样的事情(在我的 TryException.php 文件中):

public function getValue($stringKey) {
    if($this->result[$yellow] !== NULL)
    {
        return $this->result[$yellow];
    }
    else
    {
        throw new NullPointerException("The \"$yellow\" does not exist");
    }
}

但是当我捕捉到 NullPointerException(在 main.php 文件中)时,我不能这样做(它不会进入 catch 语句):

try
{
    $config->getValue('arcshive')
    echo 'ok';
}
catch (NullPointerException $e)
{
    echo $e->getMessage();
}

如果我抛出一个新的异常(并且我捕获了它)(不是 NullPointer)它会正常工作。

我该怎么办?

NullPointerException 是您自己的 class 扩展 PHP 异常 class?如果是这样,这应该有效。

$var = null;

try {
    if ($var !== NULL) {
        echo 'return $this->result[$yellow]';
    }
    else {
        throw new NullPointerException('The $var does not exist');
    }
} catch (NullPointerException $e) {
    echo $e->getMessage();
}

我对您的代码进行了一些更正(变量名称、代码限制器),使用标准异常,它按预期工作:

<?php

class Config
{
    private $result;

    public function getValue($stringKey)
    {
        if (isset($this->result[$stringKey])) {
            return $this->result[$stringKey];
        }
        else {
            throw new Exception("The \"$stringKey\" does not exist");
        }
    }
}

$config = new Config();
try {
    $config->getValue('arcshive');
    echo 'ok';
}
catch (Exception $e) {
    echo $e->getMessage();
}

或者您添加缺少的 NullPointerException class:

<?php

class NullPointerException extends Exception 
{
    public function __construct(string $message = "", int $code = 0, \Throwable $previous = null) {
        parent::__construct('NullPointerException: '.$message, $code, $previous);
    }
}

class Config
{
    private $result;

    public function getValue($stringKey)
    {
        if (isset($this->result[$stringKey])) {
            return $this->result[$stringKey];
        }
        else {
            throw new NullPointerException("The \"$stringKey\" does not exist");
        }
    }
}

$config = new Config();
try {
    $config->getValue('arcshive');
    echo 'ok';
}
catch (NullPointerException $e) {
    echo $e->getMessage();
}