Main Content

matlab.lang.correction.ReplaceIdentifierCorrection class

Package: matlab.lang.correction

Correct error by replacing identifier in function call

Description

Use ReplaceIdentifierCorrection objects in functions that throw an MException object. MException uses ReplaceIdentifierCorrection instances to display suggestions for incorrect identifiers in function calls.

Creation

Description

example

ric = matlab.lang.correction.ReplaceIdentifierCorrection(identifier,replacement) creates a correction that suggests replacing identifier with replacement in the function call that threw the MException object.

Input Arguments

expand all

Incorrect identifier in the function call, specified as a string scalar or character vector. identifier must be a valid MATLAB® identifier. A valid MATLAB identifier is a string scalar or character vector of alphanumerics (A–Z, a–z, 0–9) and underscores, where the first character is a letter and the length of the text is less than or equal to namelengthmax.

Suggested identifier for use in the function call, specified as a string scalar or character vector. replacement must be a valid MATLAB identifier.

Examples

collapse all

The functions walk and sprint require their input arguments to fall within different ranges, and their ranges do not overlap. To add a suggested replacement to the error message when one of these functions is called with an incorrect value, include a ReplaceIdentifierCorrection instance in each function.

Create the function walk by saving the following code in walk.m.

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

Create the function sprint by saving this code in sprint.m.

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

Call walk with an input greater than 6.5.

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

Did you mean:
>> sprint(10)

See Also

Functions

Properties

Introduced in R2019b