【问题标题】:throw new NullPointerException in php在 php 中抛出新的 NullPointerException
【发布时间】:2018-07-11 08:53:58
【问题描述】:

我有一个问题:如何在 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),它会正常工作。

我该怎么办?

【问题讨论】:

  • @B001ᛦ 我编辑了问题

标签: php exception exception-handling nullpointerexception try-catch


【解决方案1】:

NullPointerException 是您自己的类扩展 PHP Exception 类吗?如果是这样,这应该可行。

$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 类:

<?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();
}

【讨论】:

  • 谢谢,我编辑了这个问题。我觉得不是很清楚。
  • 我明白了,但仍然没有 NullPointerException 类。见Reserved ExceptionsSPL Exceptions
  • @user3563844 添加了新示例。
猜你喜欢
  • 2011-03-11
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 2012-05-23
  • 1970-01-01
相关资源
最近更新 更多