how to change the Identifier of a MException

1 次查看(过去 30 天)
How can I change the identifier of an existing MException? OR How can I create a new MException with my own cause and stack?
I want to rely on MATLAB's validateattributes functions because they are very flexible. on the other hand I have my own identifiers.
One way is:
try
validateattributes(...);
catch me
me2 = MException('My:Own:Identifier', me.message);
me2 = addCause(me2, me)
end
This way me2.identifier, me2.message are correct, but me2.stack is empty. I can find the stack in me2.cause{1}.stack but I would like to have it in me2.stack like a normal MException.

回答(1 个)

Aashray
Aashray 2025-3-26
Hello Behzad!
As far as I could get, you are asking three questions, let me address each of them one by one:
  1. We cannot modify the identifier of an existing "MException, as the “identifier” property is a read-only property. Its value can only be assigned once whilst the creation of MException object. If you want to change the identifier, you can catch the thrown exception and create an exception of your own, like the code you have shared.
  2. You cannot directly modify or copy the stack to a new exception because it is a read-only property. However, you can create a new exception and use the addCause method to add the original exception as the cause, and you can access the stack trace via new_exception.cause{1}.stack” , just like the code in the end of this answer.
  3. As mentioned, the stack trace is part of the original exception, and you cannot directly assign it to the new exception’s stack property. However, by adding the original exception as the cause, the new exception will have access to the original exception’s stack trace, which can be accessed and stored to a different variable.
You may refer to below mentioned code for more understanding:
try
% Code that causes an error
error('MyApp:ValidateAttributesError', 'Unable to validate the attributes.');
catch me
% Create a new exception with a custom identifier and message
new_exception = MException('MyApp:NewValidateAttributesError', 'An error occurred while validating the attributes.');
% Add the original exception as the cause
new_exception = addCause(new_exception, me);
% Access the stack trace from the cause
original_stack = new_exception.cause{1}.stack;
disp(original_stack);
% Throw the new exception
throw(new_exception);
end
Also, I found the below documentations very useful, attaching links to them for your reference:
  1. MException class: www.mathworks.com/help/matlab/ref/mexception.html
  2. throw function: www.mathworks.com/help/matlab/ref/mexception.throw.html
  3. addClause function: www.mathworks.com/help/matlab/ref/mexception.addcause.html
  4. “error” function: www.mathworks.com/help/matlab/ref/error.html

类别

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