What is the "penalty" for using a try/catch?
Show older comments
What is the "penalty" for using a try/Catch? E.g.,:
try
f.start()
catch ex
%Do something
end
Compared to, lets say:
ok_flag=f.start();
if (ok_flag==false)
%do something
end
Im familiar with the benefits of try/catch, but still wondering about the overhead... Furtermore, what if the "start" function of object f is declared like this:
function start(OBJ)
t=timer;
t.TimerFcn=@...
OBJ.t=t;
start(OBJ.t)
end
Will the overhead remain throughout the lifetime of the timer t?
All the best, Daniel Petrini, Stardots
5 Comments
José-Luis
on 21 Dec 2016
Is this really a bottleneck in your code?
Daniel Petrini
on 21 Dec 2016
Well, my advise would be not to worry about this. Unless you are in a really performance critical bit of code where every cycle counts (and, imo, you shouldn't be using Matlab if that's the case), this is a moot point.
To answer your question a bit better, what try/catch actually does is actually up to how the Mathworks implemented it. In C++ it would depend on what compiler/platform you are using. There might be overheads because of the extra checks, but those might be negligible in most cases.
Guillaume
on 21 Dec 2016
"Stroustroup warns ...." Matlab is nothing like C++, one is compiled the other is interpreted (with JIT optimisations), the memory management is totatally different, etc.
I agree with José-Luis, you should not worry about performance yet. I'd worry more about code clarity and resilience first, and only when you've shown try...catch to be a performance bottleneck in your application should you think about replacing it.
Note that if you have access to the prerealease of R2017a, you should read its release note, it has something relevant to your question. I'm not allowed to share what it says.
Daniel Petrini
on 21 Dec 2016
Accepted Answer
More Answers (0)
Categories
Find more on Error Handling in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!