[討論] 關於try catch rethrow函數已回收

看板MATLAB作者 (鈴弓)時間14年前 (2011/07/15 10:38), 編輯推噓2(203)
留言5則, 2人參與, 最新討論串1/2 (看更多)
版上爬文爬到,對於這三個函數有點興趣,但是help文件當中看的不是很懂... Help文件for try的例子: try do_something catch do_cleanup rethrow(lasterror) end 單看上面的例子我不是很能了解,但另外看到的例子倒是比較可以理解了: function d_in = read_image(filename) [path name ext] = fileparts(filename); try fid = fopen(filename, 'r'); d_in = fread(fid); catch ME1 % Get last segment of the error message identifier. idSegLast = regexp(ME1.identifier, '(?<=:)\w+$', 'match'); % Did the read fail because the file could not be found? if strcmp(idSegLast, 'InvalidFid') && ~exist(filename, 'file') % Yes. Try modifying the filename extension. switch ext case '.jpg' % Change jpg to jpeg filename = strrep(filename, '.jpg', '.jpeg') case '.jpeg' % Change jpeg to jpg filename = strrep(filename, '.jpeg', '.jpg') case '.tif' % Change tif to tiff filename = strrep(filename, '.tif', '.tiff') case '.tiff' % Change tiff to tif filename = strrep(filename, '.tiff', '.tif') otherwise fprintf('File %s not found\n', filename); rethrow(ME1); end % Try again, with modifed filenames. try fid = fopen(filename, 'r'); d_in = fread(fid); catch ME2 fprintf('Unable to access file %s\n', filename); ME2 = addCause(ME2, ME1); rethrow(ME2) end end end 在這邊想要請問的是: try函數底下使用的方式類似switch?當然try不是switch,我只是想要問 寫法是否相似?兩者的差別在哪? 舉例:switch的場合。 舉例:try的場合。 for i = [1 2 3 4 5]; for i = [1 2 3 4 5]; switch i try case {1} matlab_command case {2} catch ME1 case {3} if case {4} switch case {5} case a end case b end otherwise rethrow(ME1) end try matlab_command catch ME2 do_cleanup rethrow(ME2) end end end (上述例子兩邊的情形不相等,只是舉例) 又,與其他程式語言相比,try catch的使用方式似乎很像是C++的goto的用法。 我這樣的理解正確嗎?有沒有更詳細的解說? 會提出「try catch很像是goto」的想法,是因為try catch函數底下,多了個 ME的旗標變數(不知道這樣說對不對);後面用的rethrow讓我覺得是非常向goto 的地方。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.123.213.195

07/15 10:44, , 1F
本文係針對版上5520篇文章(#1BERfS-S)作進一步提問
07/15 10:44, 1F

07/15 11:14, , 2F
try-catch 主要是要做錯誤處理
07/15 11:14, 2F

07/15 11:28, , 3F
嗯,樓上點醒了我。那麼try-catch能在一般情況下用嗎?
07/15 11:28, 3F

07/15 11:28, , 4F
因為我覺得這try-catch功能中很類似goto的部分很吸引人
07/15 11:28, 4F

07/15 11:49, , 5F
try-catch不是goto喔
07/15 11:49, 5F
文章代碼(AID): #1E7wWkNE (MATLAB)
文章代碼(AID): #1E7wWkNE (MATLAB)