Include variable value when throwing exception

14 Ansichten (letzte 30 Tage)
Jurgen vL
Jurgen vL am 21 Mai 2019
Beantwortet: Steven Lord am 7 Nov. 2025 um 5:22
I have a function that throws a specific exception, and a try/catch block in a top-level function that handles it. I want to pass along the value of some variables in addition to the error message for debugging purposes. Typically cell array, string array or numerical matrix.
I'm guessing I would have to create a custom exception class for this?
Follow-up: Why is the default MException so restrictive? Is error handling like I described a bad practice?
  2 Kommentare
Marc Youcef
Marc Youcef am 22 Mär. 2020
I was looking for same thing as well. I hav objects being instantiated in a loop and when it fails I would like to know which index of instantiation failed.
Daniel
Daniel am 6 Nov. 2025 um 15:37
Bearbeitet: Daniel am 6 Nov. 2025 um 15:38
You can subclass MException and add any custom properties to do exactly that. See my answer.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Daniel
Daniel am 6 Nov. 2025 um 15:38
Bearbeitet: Daniel am 6 Nov. 2025 um 15:39
To add custom data to an exception, subclass MException and add custom properties.
classdef MyException < MException
properties
Data
end
end
Then, in code, use your custom property as so:
try
ex = MyException('root:cause', 'error message');
ex.Data = 1234;
ex.throw()
catch ME
disp(ME.Data)
end

Steven Lord
Steven Lord am 7 Nov. 2025 um 5:22
Why not just build up the appropriate string containing the message with the information you want it to include then call error to throw an error with that message?
expectsOnlyScalar(pi)
Good, you passed in the scalar value 3.1416
expectsOnlyScalar(1:10)
Error using solution>expectsOnlyScalar (line 9)
I expected a scalar value but instead you passed in an array of size [1 10]!
function expectsOnlyScalar(x)
if isscalar(x)
disp("Good, you passed in the scalar value " + x)
else
msg = "I expected a scalar value but instead " + ...
"you passed in an array of size " + mat2str(size(x)) + "!";
error(msg)
end
end

Kategorien

Mehr zu Error Handling finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by