Main Content

matlab.lang.correction.ReplaceIdentifierCorrection 类

命名空间: matlab.lang.correction

通过替换函数调用中的标识符来更正错误

自 R2019b 起

描述

在引发 MException 对象的函数中使用 ReplaceIdentifierCorrection 对象。MException 使用 ReplaceIdentifierCorrection 实例来显示针对函数调用中不正确标识符的建议。

创建对象

描述

示例

ric = matlab.lang.correction.ReplaceIdentifierCorrection(identifier,replacement) 创建一项更正,建议将 identifier 替换为在引发 MException 对象的函数调用中的 replacement

输入参量

全部展开

函数调用中的不正确标识符,指定为字符串标量或字符向量。identifier 必须为有效的 MATLAB® 标识符。有效的 MATLAB 标识符是由字母数字(A–Z、a–z、0–9)和下划线构成的字符串标量或字符向量,其中第一个字符应为字母且文本长度须小于或等于 namelengthmax

建议在函数调用中使用的标识符,指定为字符串标量或字符向量。replacement 必须为有效的 MATLAB 标识符。

示例

全部折叠

函数 walksprint 要求其输入参量在不同范围内,并且其范围不重叠。要在使用不正确的值调用其中一个函数时在错误消息中添加建议的替换,请在每个函数中包含一个 ReplaceIdentifierCorrection 实例。

通过将以下代码保存在 walk.m 中创建函数 walk

function walk(speed)
if speed > 6.5
    ric = matlab.lang.correction.ReplaceIdentifierCorrection('walk', 'sprint');
    error(ric, 'walk:maxSpeed', 'Cannot walk faster than 6.5 km/h.')
elseif speed <= 0
    error('walk:minSpeed', 'Speed must be greater than zero.')
end
fprintf('You are walking at a speed of %2.2f km/h.\n', speed)
end

通过将以下代码保存在 sprint.m 中创建函数 sprint

function sprint(speed)
if speed <= 6.5
    ric = matlab.lang.correction.ReplaceIdentifierCorrection('sprint', 'walk');
    error(ric, 'sprint:minSpeed', 'Cannot sprint slower than 6.5 km/h.')
elseif speed > 20
    error('sprint:maxSpeed', 'Cannot sprint faster than 20 km/h.')
end
fprintf('You are sprinting at a speed of %2.2f km/h.\n', speed)
end

使用大于 6.5 的输入调用 walk

walk(10)
Error using walk (line 4)
Cannot walk faster than 6.5 km/h.

Did you mean:
>> sprint(10)

版本历史记录

在 R2019b 中推出

另请参阅

函数

属性