Main Content

rethrow

R2026b

(Not recommended) Reissue error

rethrow called with a structure is not recommended. Call rethrow with an MException object. For more information, see Version History.

Description

rethrow(errorStruct) reissues the error specified by errorStruct. The currently running function terminates and control returns to the keyboard (or to any enclosing catch block).

Examples

collapse all

Use rethrow in a try, catch statement to reissue an error from a catch block after performing a catch-related operation.

In this example, the catch block displays a custom message and then reissues the error generated by calling primes with an invalid input argument. The rethrow function preserves the previous error information, displaying the message text and stack information.

try
   p = primes(1:10)
catch
   disp("PRIMES failed with argument '1:10'.")
   rethrow(lasterror)
end
PRIMES failed with argument '1:10'.
Error using primes (line 16)
Error using primes (line 16)
N must be a scalar

Input Arguments

collapse all

Error reporting information, specified as a scalar structure. The structure must contain at least one of the fields in this table. The rethrow function ignores any additional fields in errorStruct.

FieldnameDescription
message

Error message, specified as a text scalar. The rethrow function displays the message as specified and does not convert special characters.

If you do not specify a value for this field, the error message defaults to ''.

identifier

Error identifier, specified as a text scalar. For more information about error identifiers, see MException.

If you do not specify a value for this field, the error identifier defaults to ''.

stack

Stack trace information for the error, specified as a structure array with the following fields. The structure array has the same format as the structure returned by dbstack("-completenames"). The rethrow function ignores any additional fields in stack.

  • file — Absolute path of the file in which the function appears.

  • name — Name of the function within the file.

  • line — Line number of the function call. If you specify a noninteger value, rethrow uses only the real, integer part. The rethrow function also replaces invalid line values, such as NaN or Inf, with 0.

If you do not specify a value for the stack field, the stack trace information for the error defaults to a 0-by-1 structure with the fields file, name, and line.

Tips

If the stack field is specified, the stack of the rethrown error will be set to that value. Otherwise, the stack will be set to the line at which the rethrow occurs.

Extended Capabilities

expand all

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

Version History

Introduced before R2006a

expand all