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.
There are many similar questions on stackexchnage, but I am interested in this particular scenario.