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.
Exceptional handling should only be done or used in exceptional cases.
In a scenario which depends on whether a File exists or not it doesn't make sense to use try catch block when simply you can do
if(File.Exists(path))
{
}
else
{
}
Exceptional handling cause a lot of performance hit so try to minimize the exceptional cases by applying more check in your code like if File.Exists(path))
For this you know the file exit problem. So you prefer if else.
If you don't know the problem, better to use try catch.
i suggest the both, like below
try
{
if(File.Exists(path))
{
do work
}
else
{
messagebox.show("File Path Not Exit");
}
}
catch(Exception e)
{
messagebox.show(e);
}
it catch all the errors, which we not think.
You should never use try/catch for flow control.
Generating an exception is an extremely expensive action. If/else is much faster and cleaner.
When the file is expected to not exist, check for existence first. But when the missing file is a unusual state you should indicate this exceptional state with an exception.
So the basic idea is: Try to avoid exceptions on expectable circumstances.
Generally you should do both. try/catch to avoid exceptional situations (file was suddenly deleted from another thread). And if/else to handle non-exceptional (check if file exists). Try/catch is relatively slower than a usual if/else so it does not worth to use it for everything.