catch or catch something? - Try, catch, end.

16 ビュー (過去 30 日間)
Qianqian Pan
Qianqian Pan 2017 年 11 月 2 日
編集済み: Qianqian Pan 2019 年 2 月 15 日
Hi, I'm using the try...catch...end to catch the error. I have seen different ways of using catch at different places and got slightly confused.
One place I saw: try ... catch ... end
And another place I saw: try ... catch err ... end
And at another place I saw: try ... catch ME ... end
I'm wondering in what cases should I use catch, and what cases I need to use catch followed by some words or variables?
Many thanks.
Lily
  1 件のコメント
Adam
Adam 2017 年 11 月 2 日
編集済み: Adam 2017 年 11 月 2 日
It's the same as most code really. Your usage will tell you which you need (there are only two options there though, the last two are the same, just with a different variable name). If you want to do something relative to a specific error then you need the variable in order to interrogate it, usually something like
try...
catch ME
if strcmp( ME.identifier, someSpecificIdentifier )
doSomething()
else
rethrow( ME )
end
end
Generally I would advise using the variable. If you don't need it Matlab will just underline it in orange anyway and tell you you can get rid of it.
Without testing the type of error you are literally catching every possible error though, which is dangerous. Even syntax errors will just get caught and reacted to the same as others.

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

採用された回答

Rik
Rik 2017 年 11 月 2 日
If you take a look at the documentation, you can see that catch ME stores the exception (all error information) in the variable ME. This can be useful if there are multiple errors that you expect to occur, so you can vary your response based on information like the error ID.
You will also need the exception if you want to throw, rethrow or throwascaller.

その他の回答 (1 件)

M
M 2017 年 11 月 2 日
According to the matlab doc, you should use:
try
code1
catch
end
to catch any exception generated by the code1 and
try
code1
catch ME
end
if you want to handle different types of errors generated by code1.

カテゴリ

Help Center および File ExchangeAdding custom doc についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by