フィルターのクリア

Custom error messages with Class Object

10 ビュー (過去 30 日間)
Michael Savage
Michael Savage 2020 年 4 月 3 日
コメント済み: Michael Savage 2020 年 4 月 9 日
Hello everyone,
I have a dynamic properties class I am creating to hold some experimental data. This code will be used by other users so I want to make any error messages associated with it more helpful. When you try to address a property not in the 'properties' list you get an error similar to below:
ex.Test = 1;
The error message I get reads:
"Unrecognized property 'Test' for class 'experimentStructureClass'."
I would like to modify the error message to that it directs people to used the ex.addprop() function to add a property.
Does anyone know how to access the error messages that arise from this?
Thanks a lot,
Michael
  2 件のコメント
Ameer Hamza
Ameer Hamza 2020 年 4 月 9 日
Tommy, Good example. This is exactly what the OP asked to do. I suggest adding this as an answer to this question.
Tommy
Tommy 2020 年 4 月 9 日
Absolutely - good call.

サインインしてコメントする。

採用された回答

Tommy
Tommy 2020 年 4 月 9 日
Have a look at subsref and subsasgn.
This way you can access the error message before it is thrown. A crude example:
classdef Example
properties (SetAccess = private)
Prop1 = rand
end
methods
function varargout = subsref(obj,s)
try
[varargout{1:nargout}] = builtin('subsref',obj,s);
catch ME
error([ME.message ' Use setProp().']);
end
end
function obj = subsasgn(obj,s,varargin)
try
obj = builtin('subsasgn',obj,s,varargin{:});
catch ME
error([ME.message ' Use setProp().']);
end
end
end
end
You'd probably want to do a little more work determining what error was thrown before deciding to throw your custom error instead.
  1 件のコメント
Michael Savage
Michael Savage 2020 年 4 月 9 日
This is great starting point for me, thank you very much!

サインインしてコメントする。

その他の回答 (1 件)

Anmol Dhiman
Anmol Dhiman 2020 年 4 月 9 日
Hi Michael,
The above functionality can be achieved using Exception Handling. You can modify the error displayed by catching the exception in try block and rewriting your own error message in the catch block.
For more information on how to do the above, you can refer to below documentation page.
If you face any issues in implementing it, let me know.
Thanks,
Anmol
  1 件のコメント
Michael Savage
Michael Savage 2020 年 4 月 9 日
Thank you for your response, I have used error handling code before in scripts and functions. I just did not know how to implement it into a Class Object. Obviously, the above answer has pointed me in the right direction.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by