The Dangers Of Exception Based Logic Part 2 - Filesystem Interaction
I have often time seen filesystem interaction code that heavily depends on exception handling. Code out in the wild rarely exposes this problem in such a trivial way as my example code below, but just wanted to give another example.
Exception Based Logic: | 14-21ms |
Preemptive Error Checking Based Logic: | 0ms |
static void Main(string[] args)
{
using (new QuickTimer("Exception Based Logic"))
{
for (int i = 0; i < 10; i++)
{
try
{
string userInputPath = @"C:\not\a\real\path\foo\bar.txt";
File.WriteAllText(userInputPath, "Some String To Write");
} catch (Exception ex)
{
Console.WriteLine("Error");
}
}
}
using (new QuickTimer("Preemptive Error Checking Based Logic"))
{
for (int i = 0; i < 10; i++)
{
string userInputPath = @"C:\not\a\real\path\foo\bar.txt";
if (!File.Exists(userInputPath))
{
Console.WriteLine("Error");
continue;
}
File.WriteAllText(userInputPath, "Some String To Write");
}
}
}