You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在void类型函数中抛出异常?PHP函数abc修改求助

解决方案

首先纠正你代码里的拼写错误:trow 应该写成 throw。接下来分两种常见场景实现你的需求:

场景1:禁止传入空字符串

如果你的“未设置”指的是传入的字符串为空(比如''),可以通过判断字符串是否为空来抛出异常:

public function abc(string $string): void
{
    if (empty($string)) {
        throw new Exception("字符串不能为空");
    }
    $this->string = $string;
}

或者更严谨地判断是否为空白字符串(包含空格、换行等无效内容):

public function abc(string $string): void
{
    if (trim($string) === '') {
        throw new Exception("字符串不能为空白内容");
    }
    $this->string = $string;
}

场景2:禁止不传入参数(参数未提供)

如果你的“未设置”指的是调用函数时完全不传入$string参数,PHP 7+中声明了string $string的参数是必填项,调用时不传会自动抛出TypeError。如果要自定义异常信息,可以把参数设为可选并默认null,再做判断:

public function abc(?string $string): void
{
    if ($string === null) {
        throw new Exception("必须传入字符串参数");
    }
    $this->string = $string;
}

额外建议:如果需要更精准的异常语义,推荐使用PHP内置的InvalidArgumentException替代通用的Exception,更贴合参数校验的场景。

内容的提问来源于stack exchange,提问作者perh22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:30:53