try and catch help

6 ビュー (過去 30 日間)
Leor Greenberger
Leor Greenberger 2011 年 10 月 3 日
In a callback function of a GUIDE gui, I have:
path = get(handles.path_text,'String')
try
data = importdata(path,'')
if istruct(data)
x_k = data.data;
else
x_k = data;
end
x_k_length = length(x_k);
catch err
error(end+1) = {'Error: Invalid input path.'};
fail_status = onfail(handles.check_path);
end
The idea here is if the input path is invalid, it will be caught and handeled so the callback function can continue. However, for some reason, when MATLAB executes the IF statement, it goes to the catch block. I don't understand why.

採用された回答

Leor Greenberger
Leor Greenberger 2011 年 10 月 3 日
OOPS! should be two s's in isstruct.
getReport(err) in the catch block allowed me to solve it.

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2011 年 10 月 3 日
Please do not attempt to use error() as a variable name, especially considering the importance of error() to the try/catch mechanism!
I would tend to suspect that you do not want to use the empty string as the column delimiter.
Are you sure that path is non-empty and a regular string (not a cell array)? Should you not be checking with isempty() and ischar() ?
  1 件のコメント
Leor Greenberger
Leor Greenberger 2011 年 10 月 3 日
oops. I actually was using error(k) here as a cell array of strings. Did not realize there is an error function as well.. will change the name.

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


David Young
David Young 2011 年 10 月 3 日
A better solution, and better practice in general, is for the code in the catch block to check the identifier of the error. If it can't handle it properly, it should rethrow the error, so it is reported correctly. In your case the catch block could check err.identifier to see that it was really thrown because of an invalid input path.
Also, since you are only expecting to deal with errors that come from importdata, it might be better to only have that statement in the try block:
try
data = importdata(...);
catch
...
end
if isstruct ...
  2 件のコメント
Leor Greenberger
Leor Greenberger 2011 年 10 月 3 日
I put the isstruct stuff in the try block because if importdata fails, then I did not want to perform the if isstruct statement, as this would not make sense.
David Young
David Young 2011 年 10 月 3 日
Yes, fair enough. I was thinking in terms of the catch block doing some error recovery or else making an early exit from the function.

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by