Try/Catch or test parameters
Posted
by
Ondra Morský
on Programmers
See other posts from Programmers
or by Ondra Morský
Published on 2012-11-30T10:20:13Z
Indexed on
2012/11/30
11:20 UTC
Read the original article
Hit count: 222
clean-code
I was recently on a job interview and I was given a task to write simple method in C# to calculate when the trains meet. The code was simple mathematical equation. What I did was that I checked all the parameters on the beginning of the method to make sure, that the code will not fail.
My question is: Is it better to check the parameters, or use try/catch?
Here are my thoughts:
- Try/catch is shorter
- Try/catch will work always even if you forget about some condition
- Catch is slow in .NET
- Testing parameters is probably cleaner code (Exceptions should be exceptional)
- Testing parameters gives you more control over return values
I would prefer testing parameters in methods longer than +/- 10 lines, but what do you think about using try/catch in simple methods just like this – i.e. return (a*b)/(c+d);
There are many similar questions on stackexchnage, but I am interested in this particular scenario.
© Programmers or respective owner