When writing code, how does one decide between using if/else or try/catch? For example, in checking for a file, should this be based on if/else (if (File.Exists)) or a try/c
If you think the operation should normally succeed, then try/catch
can be easier to read. Especially, if there are many reasons for failure (multiple catch
blocks).
Otherwise, if it sometimes succeeds and sometimes fails - and does so for a specific reason, use if/else
(this is known as structured exception handling).
Some people point out how exception handling with try/catch
can be time consuming. I tend to read advice like that along the following lines: Don't do this in a tight inner loop, if your profiling indicates a performance problem. When coding your first draft, don't bother thinking about optimizing at this level at all!
in general it depends
For file based stuff you almost always want to try the operation and handle failures rather than check first. the reason being that the file system is a shared resource and you cannot guarantee that after file.exists returns true the file does exist as some other process may have deleted it in the mean time.
Just to put the topic to rest (yes, the question was posed 8 months ago, but the internet always knows!), I decided to run a little test for which is more efficient if you're pretty sure you won't have an exception -- e.g., the "else" part is going to only happen 0.001% of the time. As it turns out, if you never have to catch/else anything, the try-catch is about 4% faster (on my machine, anyway). Here's the code and the accompanying results:
CASE 1: if-else:
var startTime = DateTime.Now;
int bazillion = 100000000;
int[] list = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
for (int i = 0; i < bazillion; i++)
{
for (int k = 0; k < list.Length; k++)
{
if (k >= 0)
{
list[k] = i;
}
else
{
// do nothing.
}
}
}
var executionTime = DateTime.Now - startTime;
Debug.WriteLine (executionTime.TotalMilliseconds);
Execution times (milliseconds) on 5 runs: 7441.4256, 7392.4228, 7545.4316, 7531.4308, 7323.4188.
Average = 7446.82592 milliseconds
CASE 2: try-catch:
var startTime = DateTime.Now;
int bazillion = 100000000;
int[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
for (int i = 0; i < bazillion; i++)
{
for (int k = 0; k < list.Length; k++)
{
try
{
list[k] = i;
}
catch (Exception e)
{
// do nothing
}
}
}
var executionTime = DateTime.Now - startTime;
Debug.WriteLine(executionTime.TotalMilliseconds);
Execution times (milliseconds) on 5 runs: 7258.4152, 7137.4083, 7070.4044, 7052.4033, 7120.4073 Average = 7127.8077 milliseconds
Conclusion (based on this rather simplistic example; actual mileage may vary, etc):
In terms of sheer numbers, if you're pretty dang sure that the exception/else case will not occur, try-catch is about 4% faster than having to execute the "if" clause every single time.