Is there any other way than try & catch to handle error in matlab?

20 ビュー (過去 30 日間)
Hayatullahi Adeyemo
Hayatullahi Adeyemo 2017 年 8 月 6 日
I have a code that is executed to give a result. But it is possible that it would not execute due to some alteration done to the code before execution. How do I control the error that is expected if the code is not running. For example:
result = compute(x, y)
The value of result can be a real number or the compute function does not complete the execution. How do I assign a particular value (say -1) to result if the function fails to execute.

回答 (2 件)

Walter Roberson
Walter Roberson 2017 年 8 月 6 日
編集済み: Walter Roberson 2017 年 8 月 6 日
Do not have your function call
result = compute(x, y)
instead have it call
clear compute
result = test_function(@compute, substitute_value, x, y);
where
function output = test_function(fh, substitute_value, varargin)
try
output = feval(fh, varargin{:});
catch
output = substitute_value;
end
Now, as long as the function does not exit MATLAB or crash MATLAB, any error will be caught.
As long as only the function compute changes, and not the function test_function, then you should be fine.
Note: the above code does assume that compute() is not a function handle.

Jan
Jan 2017 年 8 月 6 日
You cannot predict reliably, if the function fails or not without running it. Such a test is impossible even in theory (search for "Turing halting problem").
You can check if the inputs cause problems inside the function also:
function r = compute(x, y)
if y == 0
r = NaN;
else
r = x / y;
end
But a try catch block is the perfect solution for catching errors, if you cannot modify the function accordingly. Why do you want to avoid it?
  4 件のコメント
Walter Roberson
Walter Roberson 2017 年 8 月 6 日
Hayatullahi Adeyemo
Hayatullahi Adeyemo 2017 年 8 月 6 日
Yes, you are right. I have modified it.

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

カテゴリ

Help Center および File ExchangeTesting Frameworks についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by