Custom exceptions private methods

조회 수: 3 (최근 30일)
Benjamin Chen
Benjamin Chen 2018년 1월 12일
댓글: Benjamin Chen 2018년 1월 12일
I would like to raise a custom error/exception when a user tries to call a private method/constructor. Suppose I have a class:
classdef MyClass
methods (Access = private)
function self = MyClass(arg1, arg2)
% Some constructor logic
end
end
methods (Static)
function myClass = createMyClass(arg1, arg2)
myClass = MyClass(arg1, arg2)
end
end
end
If I try to call:
MyClass(arg1, arg2)
it gives a not so helpful error:
Error using MyClass
Cannot access method 'MyClass' in class 'MyClass'.
I would instead like to point the user to the static method by saying:
'Construct me by calling MyClass.createMyClass.'
How would I be able to do this? Thanks!
  댓글 수: 2
Adam
Adam 2018년 1월 12일
You can customise error messages by rethrowing errors but I can't think of a way off-hand that doesn't require you to know in the first place that the code you are writing (i.e. accessing the constructor) is incorrect in order to catch the exception it throws, in which case it is pointless as you would just correct it anyway.
I have never had any objection to the default message myself - it is succinct and to the point and you can easily query class methods or look in the class definition to work out what to call instead.
Benjamin Chen
Benjamin Chen 2018년 1월 12일
I agree that generally the default message would be fine if I would be the only one using these classes or if users would look into these classes and read the documentation.
I would like however to make these classes as user friendly as possible. Sometimes it is also not obvious what should be called e.g. if I am using a builder pattern and the class is created by a separate builder class, then I think having the ability to point the user to that would be a useful feature to have.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by