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
You use try/catch when something unexpected ( an exception ) might happen and you want to do something special about it, like :
try
{
//Do something that might rise an exception, say a division by 0
//this is just an easy example as you might want to check if said value is not 0
//before dividing
int result = someNumberOfMine / anUnsafeNumber;
}
catch
{
//if something unexpected happened, do a special treament
}
In your particular case, I would recommand using File.Exists to verify the presence of the file instead of using a try/catch block since the presence or not of the file can be checked before doing anything with it.