Changing Matlab error message
조회 수: 6 (최근 30일)
이전 댓글 표시
All, my issue is this. I have 1 script that calls a function that contains many subfunctions. If one of those functions fail, I want everything to end, but I dont want the error message stack output to the command window, only the error string I specify.
I am already checking for the errors that can occur within the function, I'm just trying to get a handle on how to cleanly report to the command window that something went wrong. The end user wont care about where in the file the error is, only the error message I am outputting instead.
Alternativly, if there is a way I can simply stop all function execution programatically without using the "error" command and hence avoiding the error stack info, that would be even better.
Thanks
댓글 수: 0
답변 (2개)
Sean de Wolski
2013년 4월 30일
Use try/catch to catch the exception (error). Then throw your own error of choice inside the catch block.
try
your_fun
catch ME
error('Something')
end
For your second question, possibly. You could put the try/catch around the entire parent function contents. Then when any of the functions inside this function error, you catch it and return instead of erroring.
function fooParent
try
stuff
more stuff
other stuff
catch
return %leave
end
function subfun1
end
function subfun2
end
Now when anything errors in fooParent or it's subfunctions etc, we just return.
댓글 수: 2
Daniel Shub
2013년 4월 30일
You might want to use throwAsCaller, which will strip the stack information, instead of creating a new error. Note that this type of error handling makes debugging a real nightmare.
Sean de Wolski
2013년 4월 30일
@Daniel, I agree with the "makes debugging a nightmare part". Though:
dbstop if caught error
helps a lot.
Philip
2013년 4월 30일
댓글 수: 7
Daniel Shub
2013년 5월 1일
Unless of course ME.message is '', in which case error will not throw an error. Why do you like the old system?
Sean de Wolski
2013년 5월 1일
편집: Sean de Wolski
2013년 5월 1일
@Daniel, to be honest, I haven't given it much thought.
For the most part I try to write code that is safe guarded against exceptions and when they occur I fix them rather than try/catch them.
Actually, right now is the first time I'm working on a project (See my Friday Fun with Eval question) that includes evaluating user code and needs to be heavily safeguarded against exceptions.
This conveniently coincides with the release of the Unit Testing Framework in R2013a. What I've been doing is the following: inside of a Test method in a class than inherits from matlab.unittest.TestCase, I try the user code and catch the exception. Then fail the test with an assertion which stops the remainder of the test and provides the diagnostic from the exception.
참고 항목
카테고리
Help Center 및 File Exchange에서 Scope Variables and Generate Names에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!