well, I answered that from a really general sense.
Try Catch blocks are pretty heavy, and are designed to handle exceptions, if you know for sure that a certain scenario could occur, you should try your darnedest to handle it in normal programmatic flow, therefor it wouldn't really be an exception.
But yes, testing if an input is 0 is far more cost effective than waiting for the exception.
but you know, that doesn't mean try catch blocks don't have their place either. And in some cases, you may have great reason to handle it by catching an exception.
for example, if performance isn't your top priority, and you have some standard mechanism for handling exceptions, and in relying on the exception causes a log or audit action to take place for example.
I almost want to compare this using a simple example, and I know its not exactly what your asking, but just wanted you to see how heavy catching is..
see the integer, runtimes, I set it to 10000,
try changing that to 10, then 100, then 1000 and so on..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TimeTest {
class Program {
static void Main(string[] args) {
int parsed, runtimes = 10000;
Console.Write("Checking....");
DateTime start = DateTime.Now;
for (int i = 0; i < runtimes; i++) {
if (Int32.TryParse("ABC", out parsed)) {
continue;
} else {
continue;
}
}
DateTime end = DateTime.Now;
Console.WriteLine((end - start).ToString());
Console.Write("Catching....");
start = DateTime.Now;
for (int i = 0; i < runtimes; i++) {
try {
parsed = Int32.Parse("ABC");
continue;
} catch (Exception) {
continue;
}
}
end = DateTime.Now;
Console.WriteLine((end - start).ToString());
Console.WriteLine("Press <Enter> to terminate...");
Console.ReadLine();
}
static void x() {
for (int i = 0; i < 10000; i++) ;
return;
}
}
}
Edited by Roger, 08 December 2010 - 09:55 AM.
added code tags