Add stack to created MException object

4 vues (au cours des 30 derniers jours)
Till Rahlf
Till Rahlf le 7 Fév 2014
Réponse apportée : Gautam le 10 Fév 2025
Hi,
can I add stack Information to a created object.
I have created a MException object, like this.
myEx = MException('foo:bar','myErrString')
and I have a stack, like
myStack = struct('file','myFile','name','myName','line',42)
How can I add stack information to a MException object?
myEx = MException('foo:bar','myErrString',myStack ) does not work.

Réponses (1)

Gautam
Gautam le 10 Fév 2025
If you want to include custom stack information in an MException object, you'll need to use a workaround. One common approach is to append the stack information to the exception message or use the addCause method to attach additional information.
To manually append the stack information to the exception message you can do something like:
% Define the stack information
myStack = struct('file', 'myFile', 'name', 'myName', 'line', 42);
% Create a formatted string with stack information
stackInfo = sprintf('Error occurred in file: %s, function: %s, line: %d', ...
myStack.file, myStack.name, myStack.line);
% Create the MException object with the stack information in the message
myEx = MException('foo:bar', 'myErrString\n%s', stackInfo);
% Display the exception
disp(getReport(myEx, 'extended'));
Or, if you want to provide additional context or a secondary exception, you can use the "addCause" method:
% Create the primary MException object
myEx = MException('foo:bar', 'myErrString');
% Create a secondary MException with stack information
causeEx = MException('foo:bar:stack', 'Stack info: %s, %s, %d', ...
myStack.file, myStack.name, myStack.line);
% Add the secondary exception as a cause
myEx = myEx.addCause(causeEx);
% Display the exception with causes
disp(getReport(myEx, 'extended'));

Catégories

En savoir plus sur Exception Handling dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by