Why didn't this 'try.. catch' work?
이전 댓글 표시
If at the prompt I enter anything other than a numerical value or previously defined variable, the 'try.. catch' block does not throw an exception. Why?
try
user_input=input('Please enter a NUMERICAL input:..\n');
catch ME1
ME1
end
disp('Life goes on..');
Instead it just keep prompting me to enter an input, until I enter a valid one
채택된 답변
추가 답변 (1개)
Jos (10584)
2016년 6월 8일
1 개 추천
You should read the documentation of input which says:
" If the user enters an invalid expression at the prompt, then MATLAB displays the relevant error message, and then redisplays the prompt."
댓글 수: 7
SP Lee
2016년 6월 8일
SP Lee
2016년 6월 8일
Guillaume
2016년 6월 8일
"MATLAB displays the relevant error message" that's all it does, display. It does not throw an error, therefore there is no error to catch.
SP Lee
2016년 6월 8일
Walter Roberson
2016년 6월 8일
So it caught the error and handled it. You are not going to have any success overriding that "catch".
Guillaume
2016년 6월 8일
@SP Lee, from the point of view of the calling function there is no exception thrown by input and thus no exception to catch. Most likely, the way input does this is that it has its onw try_catch hence why MException.last gets changed. The calling code will never see this exception.
The fact that MException.last gets changed is a leakage of the implementation details of input, not something you should rely on. Unfortunately, there's plenty of such leakages in matlab.
Do what Walter told you to do, grab the input as a string and do your own validation:
user_input=input('Please enter a NUMERICAL input:..\n', 's'); %s to get a string
try
eval(sprintf('user_input = %s', user_input));
catch ME1
ME1
end
disp('Life goes on..');
SP Lee
2016년 6월 8일
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!