How can I use try/catch with conditions?

3 ビュー (過去 30 日間)
Mark Golberg
Mark Golberg 2021 年 1 月 5 日
コメント済み: Walter Roberson 2021 年 1 月 5 日
Hello,
I'd like to execute the following logic:
try
my_function(1) % connect with a certain utility
if errorMsg == 'verySpecificError' % checks if the utility is already connected
my_function(0) % first disconnect from utility and re-try to connect again
try
my_function(1) % try to connect again with utility (after verified it's in dis-connected mode)
catch
disp('problem with utility connection') % meaning there is another issue with connection.
end
else
disp('problem with utility connection') % meaning there is another issue with connection.
end
end
The purpose of the above is:
1. Try to connect
2. If there is a problem, check if it's the unique case of "you can't connect, since you're already connected".
3. If indeed, you're already connected, disconnect first, and try to connect again.
4. If there is still a problem, display an error/warning.

採用された回答

Walter Roberson
Walter Roberson 2021 年 1 月 5 日
編集済み: Walter Roberson 2021 年 1 月 5 日
try
my_function(1)
catch ME
if strcmp(ME.message, 'specific')
...
end
Note that it is better to use a message identifier so that you do not have to worry about the message having data formatted into it, and do not have to worry that the text might have been internationalized into a different language. end
  2 件のコメント
Mark Golberg
Mark Golberg 2021 年 1 月 5 日
Thanks! Exactly what I was looking for.
BTW: I'm using 'message' and not 'identifier' since it's not a standard MATLAB error, thus it doesn't gives me any identifier (empty cell).
Walter Roberson
Walter Roberson 2021 年 1 月 5 日
If you have control over that function, I would recommend coding the error() to include an identifier. You can make up your own identifiers (as long as they do not conflict with the Mathworks ones.)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeScope Variables and Generate Names についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by