Add stack to created MException object

조회 수: 3 (최근 30일)
Till Rahlf
Till Rahlf 2014년 2월 7일
답변: Gautam 2025년 2월 10일
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.

답변 (1개)

Gautam
Gautam 2025년 2월 10일
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'));

카테고리

Help CenterFile Exchange에서 Exception Handling에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by