From: Prabhakar on
Hi

I often come across situations in my code where I will have two options, one is to get away easily using try catch blocks and the other one is to add many more lines for validations.

I just wanted to know how expensive (computationally) are try catch statements?

Thanks
Prabhakar
From: Matt Fig on
I don't know what you mean by "expensive," but they are slow! Here is a function I wrote to demonstrate this. Notice that several comparisons are made in the second loop AND a function call to MOD is incurred, every time through the loop. Even with all of these comparisons and the extra function calls, the first loop is 15 times slower. Things may have changed since 2007b, and your results may vary. If the first block is faster on your machine, try taking out the call to MOD and adding another comparison which fails. I would be curious if these things have gotten faster.





function [] = trycatch()
% Demonstrate how slow try-catch blocks are.
t = [0 0];

tic
for ii = 1:10000
try
A = ii;
catch
end
end
t(1) = toc;

tic
for ii = 1:10000
if ~ii
% Never here.
elseif 0
% Never here.
elseif mod(ii,2)
B = ii;
else
C = ii;
end
end
t(2) = toc;

reltimes = t./min(t) % Display the relative times of the two loops.
From: Darren Rowland on
@ Matt,

FYI, they are just as slow in R2009a.
Darren
From: Jan Simon on
Dear Prabhakar!

> I often come across situations in my code where I will have two options, one is to get away easily using try catch blocks and the other one is to add many more lines for validations.
>
> I just wanted to know how expensive (computationally) are try catch statements?

Actually this depends crtically on the specific program. So the best idea is measure it:
tic; method1; toc
tic; method2; toc
This tells exactyl how expensive TRY-CATCH is in the individual case.

Kind regards, Jan